Aspose.Pdf

Merge Xml Files in PDF Document

Sometimes different PDF documents share some same content. For example, a number of PDF documents may have the same header or footer. In such cases, a lot of code duplication might be experienced by developers.

 

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.

 

An example code snippet is demonstrated below that uses an XSLT file using XslTransform class to combine the shared content from different XML files and produce a combined XML file that is then bound to 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 Save method of the Pdf class.

 

Note: XslTransform class is obsolete in the Microsoft .NET Framework version 2.0. The XslCompiledTransform class is the new XSLT processor. Hence we cann't use BindXML method taking XMLDocument as an input argument. So to complete that task we use BindXML method of Pdf . Please refer to the following code for merging XML files in .Net Framework 2.0

 

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>