2013-10-24 5 views
1

iTextSharp를 사용하여 XML을 PDF로 변환하는 방법은 무엇입니까? iTextSharp의 현재 XML to PDF가 명확하게 구식이며 작동하지 않습니다. 그래서 나는 문제를 고치는 것에 대해 갔다. 그러나 나는 그것을 은폐 할 수 없었다. 어느 누구도 나를 도울 수 없다.iTextSharp를 사용하여 XML을 PDF로 변환하는 방법은 무엇입니까?

<?xml version="1.0" encoding="utf-8" ?> 
<catalog> 
    <cd> 
    <SR.No>14</SR.No> 
    <test>loss test</test> 
    <code>ISO-133</code> 
    <unit>gm</unit> 
    <sampleid>36</sampleid> 
    <boreholeid>21</boreholeid> 
    <pieceno>63</pieceno> 
    </cd> 
    <cd> 
    <SR.No>24</SR.No> 
    <test>sand</test> 
    <code>ISO-133</code> 
    <unit>gm</unit> 
    <sampleid>71</sampleid> 
    <boreholeid>22</boreholeid> 
    <pieceno>23</pieceno> 
    </cd> 
    <cd> 
    <SR.No>25</SR.No> 
    <test>clay</test> 
    <code>ISO-133</code> 
    <unit>mg</unit> 
    <sampleid>52</sampleid> 
    <boreholeid>21</boreholeid> 
    <pieceno>36</pieceno> 
    </cd> 
</catalog> 
+0

당신은 아마 또한 일부 서식 규칙을 적용 할 수 있습니다하지만 당신은 그 온라인을 찾을 수 있어야합니다. 나는 대학에서 몇 년 전에 그것을 사용했다. 집에 가면 코드 샘플을 찾아 보려고합니다. Google이 충분히 힘들다면 함께 할 수있는 여러 가지 예를 찾을 수 있어야합니다. 그것은 분명히 거기에 있습니다. – Goober

+0

@Goober 감사합니다. 그러나 XML을 사용하지 않고도 테이블 구조를 만들고 여기에 데이터를 추가 할 수있는 적절한 테이블 형식으로 XML을 변환 할 수있는 요소와 특성은별로 없습니다. –

+0

나는 당신이 무슨 뜻인지 정말로 모르겠다. 근본적으로이 작업을 수행하려면 XML을 잘 이해해야합니다. – Goober

답변

2

이것은 실제로 스스로하는 것이 쉽지 않습니다. 당신은 언어를 지정하지 않았으므로 아래의 예제는 VB.Net을 사용하기 때문에 XML을보다 쉽게 ​​처리 할 수 ​​있습니다. 자세한 내용은 코드 주석을 참조하십시오. 이것은 iTextSharp 5.4.4를 목표로하고 있지만 거의 모든 버전에서 작동해야합니다.

''//Sample XML 
Dim TextXML = <?xml version="1.0" encoding="utf-8"?> 
       <catalog> 
        <cd> 
         <SR.No>14</SR.No> 
         <test>loss test</test> 
         <code>ISO-133</code> 
         <unit>gm</unit> 
         <sampleid>36</sampleid> 
         <boreholeid>21</boreholeid> 
         <pieceno>63</pieceno> 
        </cd> 
        <cd> 
         <SR.No>24</SR.No> 
         <test>sand</test> 
         <code>ISO-133</code> 
         <unit>gm</unit> 
         <sampleid>71</sampleid> 
         <boreholeid>22</boreholeid> 
         <pieceno>23</pieceno> 
        </cd> 
        <cd> 
         <SR.No>25</SR.No> 
         <test>clay</test> 
         <code>ISO-133</code> 
         <unit>mg</unit> 
         <sampleid>52</sampleid> 
         <boreholeid>21</boreholeid> 
         <pieceno>36</pieceno> 
        </cd> 
       </catalog> 

''//File to write to 
Dim TestFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf") 

''//Standard PDF creation, nothing special here 
Using fs As New FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None) 
    Using doc As New Document() 
     Using writer = PdfWriter.GetInstance(doc, fs) 
      doc.Open() 

      ''//Create a table with one column for every child node of <cd> 
      Dim T As New PdfPTable(TextXML.<catalog>.<cd>.First.Nodes.Count) 

      ''//Loop through the first item to output column headers 
      For Each N In TextXML.<catalog>.<cd>.First.Elements 
       T.AddCell(N.Name.ToString()) 
      Next 

      ''//Loop through each CD row (this is so we can call complete later on) 
      For Each CD In TextXML.<catalog>.Elements 
       ''//Loop through each child of the current CD 
       For Each N In CD.Elements 
        T.AddCell(N.Value) 
       Next 

       ''//Just in case any rows have too few cells fill in any blanks 
       T.CompleteRow() 
      Next 

      ''//Add the table to the document 
      doc.Add(T) 

      doc.Close() 
     End Using 
    End Using 
End Using 

편집

다음은 C# 버전입니다. 템플릿을 기반으로 대형 XML 문서를 작성하여 페이지 오버 플로우를 표시하는 도우미 메서드가 포함되었습니다. PdfPTable은 자동으로 여러 페이지를 스팸합니다. 후속 페이지에서 반복되도록 "헤더"로 간주되어야하는 행 수를 지정할 수 있습니다. 그것은 꽤 불쾌한 API (또는 적어도 5 년 전) (PdfPTable.DefaultCell 확인)

private XDocument createXml() { 
    //Create our sample XML document 
    var xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); 

    //Add our root node 
    var root = new XElement("catalog"); 
    //All child nodes 
    var nodeNames = new[] { "SR.No", "test", "code", "unit", "sampleid", "boreholeid", "pieceno" }; 
    XElement cd; 

    //Create a bunch of <cd> items 
    for (var i = 0; i < 1000; i++) { 
     cd = new XElement("cd"); 
     foreach (var nn in nodeNames) { 
      cd.Add(new XElement(nn) { Value = String.Format("{0}:{1}", nn, i.ToString()) }); 
     } 
     root.Add(cd); 
    } 

    xml.Add(root); 

    return xml; 
} 

private void doWork() { 
    //Sample XML 
    var xml = createXml(); 

    //File to write to 
    var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf"); 

    //Standard PDF creation, nothing special here 
    using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) { 
     using (var doc = new Document()) { 
      using (var writer = PdfWriter.GetInstance(doc, fs)) { 
       doc.Open(); 

       //Count the columns 
       var columnCount = xml.Root.Elements("cd").First().Nodes().Count(); 

       //Create a table with one column for every child node of <cd> 
       var t = new PdfPTable(columnCount); 

       //Flag that the first row should be repeated on each page break 
       t.HeaderRows = 1; 

       //Loop through the first item to output column headers 
       foreach (var N in xml.Root.Elements("cd").First().Elements()) { 
        t.AddCell(N.Name.ToString()); 
       } 

       //Loop through each CD row (this is so we can call complete later on) 
       foreach (var CD in xml.Root.Elements()) { 
        //Loop through each child of the current CD. Limit the number of children to our initial count just in case there are extra nodes. 
        foreach (var N in CD.Elements().Take(columnCount)) { 
         t.AddCell(N.Value); 
        } 
        //Just in case any rows have too few cells fill in any blanks 
        t.CompleteRow(); 
       } 

       //Add the table to the document 
       doc.Add(t); 

       doc.Close(); 
      } 
     } 
    } 
} 
+0

감사합니다. 나는 C#을 사용하고 있습니다. C#에서 코드가 필요합니다. 그래도 내 경우 정적 필드는 pdf 생성 중에도 동일하게 유지됩니다. 데이터 (테스트 번호, 단위, 코드 등은 동적으로됩니다. 그 정적 필드 나 레이블에 붙어있어서 XMl에있는 데이터가 매우 크기 때문에 새 페이지를 계속 추가해야하며 보고서를 생성하기 위해 여러 PDF 페이지가 필요합니다. 따라서 정의 된 테이블은 동일하게 유지되어야합니다 데이터가 특정 레이블이나 필드에 올바르게 첨부되어야합니다. –

+0

C# 버전을 공유해 주셔서 감사합니다. 헤더가 세로 형식이고 열이 헤더를 선언 한 후 페이지 당 6 개를 넘지 않아야하므로 수정해야합니다. 고마워 크리스. –

관련 문제