How can convert XML to PDF using iTextSharp?

匿名 (未验证) 提交于 2019-12-03 08:28:06

问题:

How can convert XML to PDF using iTextSharp? the iTextSharp's current XML to PDF is clearly out of date and does not work. So I went about fixing the problem but i am not been able to covert it Can any one help me.

<?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:

This is really trivial to do on your own. You didn't specify a language so the sample below uses VB.Net since (I think) it handles XML more easily. See the code comments for more details. This is targeting iTextSharp 5.4.4 but should work with pretty much any version.

''//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 

EDIT

Here's a C# version. I've included a helper method to create a large XML document based on your template to show page overflow. The PdfPTable will automatically spam multiple pages. You can specify the number of rows that should be considered a "header" so that they repeat on subsequent pages. You'll probably want to also apply some formatting rules but you should be able to find those online (look for 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();             }         }     } } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!