1

如何使用 iTextSharp 将 XML 转换为 PDF?iTextSharp 当前的 XML to 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>
4

1 回答 1

3

自己做这件事真的很简单。您没有指定语言,因此下面的示例使用 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自动向多个页面发送垃圾邮件。您可以指定应被视为“标题”的行数,以便它们在后续页面上重复。您可能还想应用一些格式规则,但您应该能够在网上找到这些规则(查找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();
            }
        }
    }
}
于 2013-10-25T18:45:57.173 回答