如何使用iTextSharp将XML转换为PDF?

时间:2013-10-24 12:41:06

标签: asp.net xml itextsharp

如何使用iTextSharp将XML转换为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>

1 个答案:

答案 0 :(得分: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();
            }
        }
    }
}