Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » XML
Language: .NET
Expertise: Intermediate
Mar 17, 2011

Merge XML files into a PDF Document in .NET

Sometimes different PDF documents have some content in common. For example, a number of PDF documents may have the same header or footer. In such cases, .NET developers who are responsible for document creation might go through a lot of code duplication. To reduce this code duplication, it's a good practice to save the content (shared by multiple PDF documents) into different XML files and then merge the XML files together before generating PDF documents.

The example code snippets below use an XSLT file using the XslTransform class to combine the shared content from different XML files and produce a combined XML file. The combined XML file is then bound to a PDF object by calling its BindXML method. After the final XML file is bound, then it can be saved as a PDF document by calling the save method of the PDF class.

Example: .NET Framework 2.0 and VS 2005

C#

FileStream fs1 = new FileStream(@"D:\AsposeTest\Example.xml", FileMode.Open);
FileStream fs2 = new FileStream(@"D:\AsposeTest\Example.xslt", FileMode.Open);
 
Pdf pdf1 = new Pdf();
 
pdf1.BindXML(fs1, fs2);
 
pdf1.Save("D:/Asposetest/XMlXSLTMERGE.pdf");
 
fs1.Close();
fs2.Close();

Example: .NET Framework 1.1 and VS 2003

C#

XmlDocument xmlDoc = new XmlDocument();
MemoryStream ms = new MemoryStream(); 
 
XslTransform xsl = new XslTransform(); 
xsl.Load("test.xslt"); 
xsl.Transform(xmlDoc,null,ms); 
 
ms.Position = 0; 
xmlDoc.Load(ms); 
ms.Close(); 
 
Pdf pdf = new Pdf(); 
pdf.BindXML(xmlDoc,null); 
 
pdf.Save("e:/temp/test.pdf");

VB.NET

Dim xmlDoc As XmlDocument = New XmlDocument()
Dim ms As MemoryStream = New MemoryStream()
 
Dim xsl As XslTransform = New XslTransform()
xsl.Load("test.xslt")
xsl.Transform(xmlDoc, Nothing, ms)
 
ms.Position = 0
xmlDoc.Load(ms)
ms.Close()
 
Dim pdf As Pdf = New Pdf()
pdf.BindXML(xmlDoc, Nothing)
 
pdf.Save("e:/temp/test.pdf")

test.xslt

<?xml version="1.0" encoding="utf-8" ?> 
  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
   <xsl:template match="/"> 
       <Pdf xmlns="Aspose.Pdf"> 
         <Section> 
                 <Header> 
                         <xsl:copy-of select="document('header.xml')"/> 
                 </Header> 
                 <xsl:copy-of select="document('content.xml')"/> 
         </Section> 
       </Pdf> 
   </xsl:template> 
</xsl:stylesheet>

header.xml

<Text> 
        <Segment>header</Segment> 
</Text>

content.xml

<Text> 
         <Segment>Hello world</Segment> 
</Text>

Find out more about Aspose.Pdf for .NET at their website.

Azam Sher
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap