/*
 * Copyright 2015 Datalogics, Inc.
 */

package com.datalogics.pdf.samples.rendering;

import com.adobe.pdfjt.core.license.LicenseManager;
import com.adobe.pdfjt.pdf.document.PDFDocument;
import com.adobe.pdfjt.pdf.page.PDFPage;
import com.adobe.pdfjt.services.rasterizer.PageRasterizer;
import com.adobe.pdfjt.services.rasterizer.RasterizationOptions;

import com.datalogics.pdf.samples.util.DocumentUtils;
import com.datalogics.pdf.samples.util.FontUtils;
import com.datalogics.pdf.samples.util.IoUtils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

/**
 * This sample shows how to render the pages of a PDF. The higher the resolution, the larger heap you'll need.
 */
public final class RenderPdf {

    private static final int RESOLUTION = 300;
    private static final Logger LOGGER = Logger.getLogger(RenderPdf.class.getName());
    public static final String DEFAULT_INPUT = "/com/datalogics/pdf/samples/printing/pdfjavatoolkit-ds.pdf";

    private static PageRasterizer pageRasterizer;

    /**
     * This is a utility class, and won't be instantiated.
     */
    private RenderPdf() {}

    /**
     * Main program.
     *
     * @param args command line arguments
     * @throws Exception a general exception was thrown
     */
    public static void main(final String... args) throws Exception {
        // If you are using an evaluation version of the product (License Managed, or LM), set the path to where
        // PDFJT can find the license file.
        //
        // If you are not using an evaluation version of the product you can ignore or remove this code.
        LicenseManager.setLicensePath(".");
        URL inputUrl = null;
        if (args.length > 0) {
            inputUrl = IoUtils.createUrlFromPath(args[0]);
        } else {
            inputUrl = RenderPdf.class.getResource(DEFAULT_INPUT);
        }

        renderPdf(inputUrl);
    }

    /**
     * Render the specified PDF at the default resolution.
     *
     * @param inputUrl path to the PDF to render
     * @throws Exception a general exception was thrown
     */
    public static void renderPdf(final URL inputUrl) throws Exception {
        renderPdf(inputUrl, RESOLUTION);
    }


    /**
     * Render the specified PDF.
     *
     * @param inputUrl path to the PDF to render
     * @param resolution the desired resolution in dpi
     * @throws Exception a general exception was thrown
     */
    public static void renderPdf(final URL inputUrl, final int resolution) throws Exception {
        // Only log info messages and above
        LOGGER.setLevel(Level.INFO);

        // Read the PDF input file and detect the page size of the first page. This sample assumes all pages in
        // the document are the same size.
        final PDFDocument pdfDocument = DocumentUtils.openPdfDocument(inputUrl);
        final PDFPage pdfPage = pdfDocument.requirePages().getPage(0);
        final int pdfPageWidth = (int) pdfPage.getMediaBox().width();
        final int pdfPageHeight = (int) pdfPage.getMediaBox().height();

        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("Resolution: " + resolution + " DPI");
        }

        // Create a set of options that will be used to rasterize the pages. We use the page width, height, and the
        // desired resolution to tell the Java Toolkit what dimensions the bitmap should be.
        final RasterizationOptions rasterizationOptions = new RasterizationOptions();
        rasterizationOptions.setFontSet(FontUtils.getDocFontSet(pdfDocument));
        rasterizationOptions.setWidth(pdfPageWidth / 72 * resolution);
        rasterizationOptions.setHeight(pdfPageHeight / 72 * resolution);

        // Use a PageRasterizer to create a bitmap for each page.
        pageRasterizer = new PageRasterizer(pdfDocument.requirePages(), rasterizationOptions);

        final String imageBaseName = new File(inputUrl.toURI()).getName();
        int pageNo = 0;

        while (pageRasterizer.hasNext()) {
            pageNo += 1;
            final BufferedImage page = pageRasterizer.next();
            savePage(imageBaseName, pageNo, page);

        }
    }

    /**
     * Save one page to a PNG file.
     *
     * @param imageBaseName the base name for the PNG file
     * @param pageNo the pageNumber
     * @param page the image of the page
     * @throws IOException an I/O operation failed or was interrupted
     */
    private static void savePage(final String imageBaseName, final int pageNo, final BufferedImage page)
                    throws IOException {
        final File outputFile = new File(imageBaseName + "." + pageNo + ".png");
        // Saving raster image
        ImageIO.write(page, "png", outputFile);
    }
}

@@ -589,16 +589,52 @@
 eption;%0A
+import java.net.URISyntaxException;%0A
 import j
@@ -2679,32 +2679,698 @@
 ows Exception %7B%0A
+        final String imageBaseName = new File(inputUrl.toURI()).getName();%0A        final URL outputBaseUrl = new File(imageBaseName).toURI().toURL();%0A        renderPdf(inputUrl, resolution, outputBaseUrl);%0A    %7D%0A%0A    /**%0A     * Render the specified PDF.%0A     *%0A     * @param inputUrl path to the PDF to render%0A     * @param resolution the desired resolution in dpi%0A     * @param outputBaseUrl the URL for the output file, to which will be added the page number and %22.png%22 extension.%0A     * @throws Exception a general exception was thrown%0A     */%0A    public static void renderPdf(final URL inputUrl, final int resolution, final URL outputBaseUrl) throws Exception %7B%0A
         // Only 
@@ -4689,83 +4689,8 @@
 );%0A%0A
-        final String imageBaseName = new File(inputUrl.toURI()).getName();%0A
     
@@ -4861,29 +4861,29 @@
 avePage(
-imageBaseName
+outputBaseUrl
 , pageNo
@@ -4891,17 +4891,16 @@
  page);%0A
-%0A
         
@@ -4986,43 +4986,39 @@
 Base
-Name
+Url
  the 
-base name for the PNG file
+URL to the image output
 %0A   
@@ -5161,16 +5161,98 @@
 rrupted%0A
+     * @throws URISyntaxException a string could not be parsed as a URI reference%0A
      */%0A
@@ -5286,30 +5286,27 @@
 ePage(final 
-String
+URL
  imageBaseNa
@@ -5303,20 +5303,19 @@
 mageBase
-Name
+Url
 , final 
@@ -5382,32 +5382,52 @@
 rows IOException
+, URISyntaxException
  %7B%0A        final
@@ -5463,20 +5463,37 @@
 mageBase
-Name
+Url.toURI().getPath()
  + %22.%22 +

Allow the specification of a base file name for the output