My college Oliver Guhr wroted a nice blogpost about PDF creation with nFop. The post is in german - but just scroll down to download the soure code.
Today I wanted to show you, how you could create a PDF by just clicking a link on a webpage. Oliver helped me again and wrote the source code of this blog post:
First step: J# dlls
I only have Visual Studio 2008 installed - without the Visual J# library - the "vjslib.dll". You need this dll for nFop. If you don´t have this dll, just download it here: Visual J# Redistributable Packages
The solution: A generic handler
It´s a bit tricky to write the PDF content in the context - here is the complete source code from my ASHX:
<%@ WebHandler Language="C#" Class="PdfHandler" %> using System; using System.Data; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Services.Protocols; using java.io; using org.xml.sax; using org.apache.fop.apps; using System.IO; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class PdfHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/pdf"; FileInputStream input = new FileInputStream(context.Request.PhysicalApplicationPath+"helloworld.fo"); InputSource source = new InputSource(input); java.io.ByteArrayOutputStream output = new ByteArrayOutputStream(); Driver driver = new Driver(source, output); driver.setRenderer(Driver.RENDER_PDF); driver.run(); output.close(); sbyte[] Pdf = output.toByteArray(); BinaryWriter bw = new BinaryWriter(context.Response.OutputStream); for (int i = 0; i < Pdf.Length; i++) { bw.Write(Pdf[i]); } bw.Close(); } public bool IsReusable { get { return false; } } }
A look into the solution explorer:
The helloworld.fo:
<?xml version="1.0" encoding="utf-8"?> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> <fo:layout-master-set> <fo:simple-page-master master-name="A4"³ page-width="210mm" page-height="297mm"> <fo:region-body region-name="xsl-region-body" margin="2cm"/> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="A4"³> <!- (in Versionen <2.0 "master-name") -> <fo:flow flow-name="xsl-region-body"> <fo:block>Hallo Welt!</fo:block> </fo:flow> </fo:page-sequence> </fo:root>
Now you can create the "helloworld" PDF by just clicking this link:
http://localhost:56602/Pdf/PdfHandler.ashx
Easy :)