PDFUtils.java [src/java/reports] Revision:   Date:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package reports;

import com.lowagie.text.DocumentException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.pdf.ITextUserAgent;
import org.xhtmlrenderer.resource.XMLResource;
import org.xml.sax.InputSource;

/**
 * Utility class for PDF stuff
 *
 */
public final class PDFUtils {

  /**
   * This code is borrowed from the Flying Saucer library for HTML->PDF
   * conversion. Specifically, it is from their demo, "PDFRender".
   *
   * @param url Input file template
   * @param pdf Output filename
   * @throws IOException
   * @throws DocumentException
   */
  public static void createPDFFromHTML(String url, String pdf)
      throws IOException, DocumentException {
    // This code is borrowed from the Flying Saucer library for HTML->PDF conversion.
    // Specifically, it is from their demo, "PDFRender".
    OutputStream os = null;
    try {
      os = new FileOutputStream(pdf);

      /* standard approach
             ITextRenderer renderer = new ITextRenderer();

             renderer.setDocument(url);
             renderer.layout();
             renderer.createPDF(os);
       */
      ITextRenderer renderer = new ITextRenderer();
      ITextUserAgent callback = new ITextUserAgent(renderer.getOutputDevice());
      callback.setSharedContext(renderer.getSharedContext());
      renderer.getSharedContext().setUserAgentCallback(callback);

      Document doc = XMLResource.load(new InputSource(url)).getDocument();

      renderer.setDocument(doc, url);
      renderer.layout();
      try {
        renderer.createPDF(os);
      } catch (Exception DocumentException) {
          //ignore?
      }

      os.close();
      os = null;
    } finally {
      if (os != null) {
        try {
          os.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }


  /**
   * Initialize Apache velocity engine.
   *
   * @param folderForHTMLImageRelativePaths working folder
   * @return velocity engine instance
   */
  public static VelocityEngine createVelocityEngine(File folderForHTMLImageRelativePaths) {
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, folderForHTMLImageRelativePaths.getPath());
    velocityEngine.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME, "reports.JSONArrayIteratingUberspector");
    velocityEngine.init();
    return velocityEngine;
  }
}