This technical tip shows how to 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.
Example: .Net Framework 2.0 and VS 2005
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
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");
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")
<?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>
<Text>
<Segment>header</Segment>
</Text>
<Text>
<Segment>Hello world</Segment>
</Text>
More about Aspose.Pdf for .NET