/****************************************************************************
 **
 ** This file is part of yFiles FLEX 1.3.2.
 **
 ** yWorks proprietary/confidential. Use is subject to license terms.
 **
 ** Unauthorized redistribution of this file or of a byte-code version
 ** of this file is strictly forbidden.
 **
 ** Copyright (c) 2006-2009 by yWorks GmbH, Vor dem Kreuzberg 28,
 ** 72070 Tuebingen, Germany. All rights reserved.
 **
 ***************************************************************************/
package com.yworks.yfiles.server.graphml.demo.servlets;

import com.yworks.yfiles.server.graphml.servlets.DownloadServlet;
import com.yworks.yfiles.server.graphml.support.Graph2DRoundtripSupport;
import y.view.Graph2D;
import yext.export.io.PDFOutputHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.print.PageFormat;
import java.io.IOException;

/**
 * Simple example which demonstrates how the yExport extension package
 * can be used to export a yFiles FLEX graph as PDF file.
 * <p>
 * Note: this example needs the yExport package installed.
 * </p>
 */
public class PdfExportServlet extends DownloadServlet {


  protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws
      ServletException, IOException {
    // Use Graph2D / Java GraphML because the graph has to be rendered on the server.
    Graph2DRoundtripSupport support = new Graph2DRoundtripSupport();
    Graph2D graph = (Graph2D) support.createRoundtripGraph();
    // Read the graph.
    support.readGraph(getGraphInputStream(httpServletRequest), graph);

    // Use the request parameters to transfer configuration options.
    // Here, the parameter "orientation" determines the page orientation.
    String orientation = httpServletRequest.getParameter("orientation");
    PageFormat pageFormat = new PageFormat();
    if ("LANDSCAPE".equals(orientation)) {
      pageFormat.setOrientation(PageFormat.LANDSCAPE);
    } else {
      pageFormat.setOrientation(PageFormat.PORTRAIT);
    }

    // Set the response parameters
    httpServletResponse.setContentType("application/pdf");
    httpServletResponse.setHeader("Content-Disposition", "attachment");
    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

    // Create and configure the PDFOutputHandler
    PDFOutputHandler handler = new PDFOutputHandler();
    handler.setPageFormat(pageFormat);
    // Write the PDF directly to the response's output stream
    handler.write(graph, httpServletResponse.getOutputStream());
  }
}
