Example usage for com.lowagie.text Document Document

List of usage examples for com.lowagie.text Document Document

Introduction

In this page you can find the example usage for com.lowagie.text Document Document.

Prototype


public Document() 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:ilarkesto.integration.itext.PdfBuilder.java

License:Open Source License

public void write(OutputStream out) {
    Document document = new Document();
    try {//from  w ww .j a  v a  2  s  . c  om
        PdfWriter.getInstance(document, out);
    } catch (DocumentException ex) {
        throw new RuntimeException(ex);
    }
    document.setMargins(mmToPoints(marginLeft), mmToPoints(marginRight), mmToPoints(marginTop),
            mmToPoints(marginBottom));
    document.open();
    for (ItextElement element : elements) {
        try {
            if (element instanceof PageBreak) {
                document.newPage();
            } else {
                Element iTextElement = element.getITextElement();
                if (iTextElement != null)
                    document.add(iTextElement);
            }
        } catch (DocumentException ex) {
            throw new RuntimeException(ex);
        }
    }
    document.close();
}

From source file:io.github.autsia.crowly.controllers.DashboardController.java

License:Apache License

@RequestMapping(value = "/campaigns/export/{campaignId}", method = RequestMethod.GET)
public ResponseEntity<byte[]> export(@PathVariable("campaignId") String campaignId, ModelMap model)
        throws DocumentException {
    Document document = new Document();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, byteArrayOutputStream);
    document.open();//w ww. j a  va 2  s  .c o m
    Gson gson = new Gson();
    String json = gson.toJson(mentionRepository.findByCampaignId(campaignId));
    document.add(new Paragraph(json));
    document.close();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
            HttpStatus.OK);
    return response;
}

From source file:is.idega.idegaweb.egov.printing.business.DocumentServiceBean.java

License:Open Source License

/**
 * Creates a pdf letter from a template which is chosen from the message type. Returns a primaryKey to a file in database
 *///from w w  w.  ja v  a2s. c om
public Integer createPDF(IWUserContext iwuc, Collection msgs, String type, String fileName,
        boolean flagPrinted) {
    OutputStream outerOs = null;
    InputStream outerIs = null;
    try {
        MemoryFileBuffer outerBuf = new MemoryFileBuffer();
        outerOs = new MemoryOutputStream(outerBuf);
        outerIs = new MemoryInputStream(outerBuf);

        //
        // step 1: creation of a document-object
        Document document = new Document();
        // step 2: we create a writer that listens to the document
        PdfCopy writer = new PdfCopy(document, outerOs);
        // step 3: we open the document
        document.open();

        ICFile bulkFile = getICFileHome().create();
        bulkFile.store();

        PrintingService pserv = getPrintingService();

        CommuneMessageBusiness msgBuiz = getMessageService();
        int lettersProcessed = 0;
        for (Iterator iter = msgs.iterator(); iter.hasNext();) {
            PrintMessage msg = (PrintMessage) iter.next();
            MemoryFileBuffer buffer = new MemoryFileBuffer();
            OutputStream mos = new MemoryOutputStream(buffer);
            InputStream mis = new MemoryInputStream(buffer);

            PrintingContext pcx = getPrintingContext(iwuc, msg);
            if (pcx != null) {
                pcx.setDocumentStream(mos);
                pserv.printDocument(pcx);

                PdfReader reader = new PdfReader(buffer.buffer());
                PdfImportedPage page;
                int n = reader.getNumberOfPages();
                for (int i = 0; i < n;) {
                    ++i;
                    page = writer.getImportedPage(reader, i);
                    writer.addPage(page);
                }
                lettersProcessed++;
                storeStreamToICFile(iwuc, msgBuiz, msg, mis, fileName, buffer.length(), flagPrinted);
                msg.setMessageBulkData(bulkFile);
                msg.store();
            }
        }
        document.close();
        bulkFile = createFile(bulkFile, fileName, outerIs, outerBuf.length());

        PrintDocuments pdocs = getPrintDocumentsHome().create();
        pdocs.setDocument(bulkFile);
        pdocs.setNumberOfSubDocuments(lettersProcessed);
        pdocs.setCreator(iwuc.getCurrentUser());
        pdocs.setType(type);
        pdocs.store();

        return (Integer) bulkFile.getPrimaryKey();
    } catch (Exception e) {
        e.printStackTrace();
        throw new ContentCreationException(e);
    } finally {
        try {
            outerOs.close();
            outerIs.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:it.eng.spagobi.engines.exporters.ChartExporter.java

License:Mozilla Public License

public File getChartPDF(String uuid, boolean multichart, String orientation) throws Exception {
    logger.debug("IN");

    File tmpFile;/* w  ww. ja va 2s  .  c o m*/

    try {
        tmpFile = null;
        String dir = System.getProperty("java.io.tmpdir");
        String path = (new StringBuilder(String.valueOf(dir))).append("/").append(uuid).append(".png")
                .toString();
        File dirF = new File(dir);
        tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF);
        Document pdfDocument = new Document();
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile));
        //pdfDocument.open();
        if (multichart) {
            pdfDocument.open();

            List images = new ArrayList();
            for (int i = 0; i < MAX_NUM_IMG; i++) {
                String imgName = (new StringBuilder(String.valueOf(path.substring(0, path.indexOf(".png")))))
                        .append(i).append(".png").toString();
                Image png = Image.getInstance(imgName);
                if (png == null) {
                    break;
                }
                images.add(png);
            }

            Table table = new Table(images.size());
            for (int i = 0; i < images.size(); i++) {
                Image png = (Image) images.get(i);
                if (HORIZONTAL_ORIENTATION.equalsIgnoreCase(orientation)) {
                    Cell pngCell = new Cell(png);
                    pngCell.setBorder(0);
                    table.setBorder(0);
                    table.addCell(pngCell);
                } else {
                    png.setAlignment(5);
                    pdfDocument.add(png);
                }
            }

            pdfDocument.add(table);
        } else {
            Image jpg = Image.getInstance(path);
            float height = jpg.getHeight();
            float width = jpg.getWidth();

            // if in need to change layout
            if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                changeLayout(pdfDocument, jpg, width, height);
            }

            pdfDocument.open();
            pdfDocument.add(jpg);
        }
        pdfDocument.close();
        docWriter.close();

        logger.debug("OUT");

        return tmpFile;

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        throw new Exception(e);
    } finally {

        //tmpFile.delete();

    }
}

From source file:it.eng.spagobi.engines.geo.service.DrawMapAction.java

License:Mozilla Public License

public void service(SourceBean serviceRequest, SourceBean serviceResponse) {

    String outputFormat = null;//from  ww  w  . j a v a  2 s  . c o m
    String executionId = null;
    File maptmpfile = null;
    boolean inlineResponse;
    String responseFileName;
    Monitor totalTimeMonitor = null;
    Monitor totalTimePerFormatMonitor = null;
    Monitor flushingResponseTotalTimeMonitor = null;
    Monitor errorHitsMonitor = null;

    logger.debug("IN");

    try {
        super.service(serviceRequest, serviceResponse);

        totalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.totalTime");

        executionId = getAttributeAsString("SBI_EXECUTION_ID");

        outputFormat = getAttributeAsString(OUTPUT_FORMAT);
        logger.debug("Parameter [" + OUTPUT_FORMAT + "] is equal to [" + outputFormat + "]");

        inlineResponse = getAttributeAsBoolean(INLINE_RESPONSE, true);
        logger.debug("Parameter [" + INLINE_RESPONSE + "] is equal to [" + inlineResponse + "]");

        if (getAuditServiceProxy() != null)
            getAuditServiceProxy().notifyServiceStartEvent();

        if (outputFormat == null) {
            logger.info("Parameter [" + outputFormat + "] not specified into request");
            outputFormat = (String) getGeoEngineInstance().getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE);
            logger.debug("Env Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] is equal to ["
                    + outputFormat + "]");
        }

        if (outputFormat == null) {
            logger.info(
                    "Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] not specified into environment");
            outputFormat = DEFAULT_OUTPUT_TYPE;
        }

        totalTimePerFormatMonitor = MonitorFactory
                .start("GeoEngine.drawMapAction." + outputFormat + "totalTime");

        try {
            if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) {
                maptmpfile = getGeoEngineInstance().renderMap(GeoEngineConstants.JPEG);

            } else {
                maptmpfile = getGeoEngineInstance().renderMap(outputFormat);
            }
        } catch (Throwable t) {
            throw new DrawMapServiceException(getActionName(), "Impossible to render map", t);
        }

        responseFileName = "map.svg";

        IStreamEncoder encoder = null;
        File tmpFile = null;
        if (outputFormat.equalsIgnoreCase(GeoEngineConstants.JPEG)) {
            encoder = new SVGMapConverter();
            responseFileName = "map.jpeg";
        } else if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) {

            encoder = new SVGMapConverter();
            BufferedInputStream bis = null;

            String dirS = System.getProperty("java.io.tmpdir");
            File imageFile = null;
            bis = new BufferedInputStream(new FileInputStream(maptmpfile));
            try {
                int contentLength = 0;
                int b = -1;
                String contentFileName = "tempJPEGExport";
                freezeHttpResponse();

                File dir = new File(dirS);
                imageFile = File.createTempFile("tempJPEGExport", ".jpeg", dir);
                FileOutputStream stream = new FileOutputStream(imageFile);

                encoder.encode(bis, stream);

                stream.flush();
                stream.close();

                File dirF = new File(dirS);
                tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF);
                Document pdfDocument = new Document();
                PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile));
                pdfDocument.open();
                Image jpg = Image.getInstance(imageFile.getPath());
                jpg.setRotation(new Double(Math.PI / 2).floatValue());
                jpg.scaleAbsolute(770, 520);
                pdfDocument.add(jpg);
                pdfDocument.close();
                docWriter.close();
                maptmpfile = tmpFile;

            } finally {
                bis.close();
                if (imageFile != null)
                    imageFile.delete();
            }

            responseFileName = "map.pdf";
            encoder = null;

        }

        try {
            flushingResponseTotalTimeMonitor = MonitorFactory
                    .start("GeoEngine.drawMapAction.flushResponse.totalTime");
            writeBackToClient(maptmpfile, encoder, inlineResponse, responseFileName,
                    getContentType(outputFormat));

        } catch (IOException e) {
            logger.error("error while flushing output", e);
            if (getAuditServiceProxy() != null)
                getAuditServiceProxy().notifyServiceErrorEvent("Error while flushing output");
            throw new DrawMapServiceException(getActionName(), "Error while flushing output", e);
        }

        if (getAuditServiceProxy() != null)
            getAuditServiceProxy().notifyServiceEndEvent();

        maptmpfile.delete();
        if (tmpFile != null)
            tmpFile.delete();

    } catch (Throwable t) {
        errorHitsMonitor = MonitorFactory.start("GeoEngine.errorHits");
        errorHitsMonitor.stop();
        DrawMapServiceException wrappedException;
        if (t instanceof DrawMapServiceException) {
            wrappedException = (DrawMapServiceException) t;
        } else {
            wrappedException = new DrawMapServiceException(getActionName(),
                    "An unpredicted error occurred while executing " + getActionName() + " service", t);
        }

        wrappedException.setDescription(wrappedException.getRootCause());
        Throwable rootException = wrappedException.getRootException();
        if (rootException instanceof SpagoBIEngineRuntimeException) {
            wrappedException.setHints(((SpagoBIEngineRuntimeException) rootException).getHints());
        }

        throw wrappedException;
    } finally {
        if (flushingResponseTotalTimeMonitor != null)
            flushingResponseTotalTimeMonitor.stop();
        if (totalTimePerFormatMonitor != null)
            totalTimePerFormatMonitor.stop();
        if (totalTimeMonitor != null)
            totalTimeMonitor.stop();

    }

    logger.debug("OUT");
}

From source file:it.eng.spagobi.engines.geo.service.initializer.ExecutionProxyGeoEngineStartAction.java

License:Mozilla Public License

public void service(SourceBean serviceRequest, SourceBean serviceResponse) throws GeoEngineException {

    GeoEngineInstance geoEngineInstance;
    Map env;//from   w  w w .  j  ava  2 s.c  om
    byte[] analysisStateRowData;
    GeoEngineAnalysisState analysisState = null;
    String executionContext;
    String executionId;
    String documentLabel;
    String outputType;

    Monitor hitsPrimary = null;
    Monitor hitsByDate = null;
    Monitor hitsByUserId = null;
    Monitor hitsByDocumentId = null;
    Monitor hitsByExecutionContext = null;

    logger.debug("IN");

    try {
        setEngineName(ENGINE_NAME);
        super.service(serviceRequest, serviceResponse);

        //if(true) throw new SpagoBIEngineStartupException(getEngineName(), "Test exception");

        logger.debug("User Id: " + getUserId());
        logger.debug("Audit Id: " + getAuditId());
        logger.debug("Document Id: " + getDocumentId());
        logger.debug("Template: " + getTemplateAsSourceBean());

        hitsPrimary = MonitorFactory.startPrimary("GeoEngine.requestHits");
        hitsByDate = MonitorFactory.start(
                "GeoEngine.requestHits." + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date()));
        hitsByUserId = MonitorFactory.start("GeoEngine.requestHits." + getUserId());
        hitsByDocumentId = MonitorFactory.start("GeoEngine.requestHits." + getDocumentId());

        executionContext = getAttributeAsString(EXECUTION_CONTEXT);
        logger.debug("Parameter [" + EXECUTION_CONTEXT + "] is equal to [" + executionContext + "]");

        executionId = getAttributeAsString(EXECUTION_ID);
        logger.debug("Parameter [" + EXECUTION_ID + "] is equal to [" + executionId + "]");

        documentLabel = getAttributeAsString(DOCUMENT_LABEL);
        logger.debug("Parameter [" + DOCUMENT_LABEL + "] is equal to [" + documentLabel + "]");

        outputType = getAttributeAsString(OUTPUT_TYPE);
        logger.debug("Parameter [" + OUTPUT_TYPE + "] is equal to [" + outputType + "]");

        logger.debug("Execution context: " + executionContext);
        String isDocumentCompositionModeActive = (executionContext != null
                && executionContext.equalsIgnoreCase("DOCUMENT_COMPOSITION")) ? "TRUE" : "FALSE";
        logger.debug("Document composition mode active: " + isDocumentCompositionModeActive);

        hitsByExecutionContext = MonitorFactory.start("GeoEngine.requestHits."
                + (isDocumentCompositionModeActive.equalsIgnoreCase("TRUE") ? "compositeDocument"
                        : "singleDocument"));

        env = getEnv("TRUE".equalsIgnoreCase(isDocumentCompositionModeActive), documentLabel, executionId);
        if (outputType != null) {
            env.put(GeoEngineConstants.ENV_OUTPUT_TYPE, outputType);
        }

        geoEngineInstance = GeoEngine.createInstance(getTemplateAsSourceBean(), env);
        geoEngineInstance.setAnalysisMetadata(getAnalysisMetadata());

        analysisStateRowData = getAnalysisStateRowData();
        if (analysisStateRowData != null) {
            logger.debug("AnalysisStateRowData: " + new String(analysisStateRowData));
            analysisState = new GeoEngineAnalysisState();
            analysisState.load(analysisStateRowData);
            logger.debug("AnalysisState: " + analysisState.toString());
        } else {
            logger.debug("AnalysisStateRowData: NULL");
        }
        if (analysisState != null) {
            geoEngineInstance.setAnalysisState(analysisState);
        }

        String selectedMeasureName = getAttributeAsString("default_kpi");
        logger.debug("Parameter [" + "default_kpi" + "] is equal to [" + selectedMeasureName + "]");

        if (!StringUtilities.isEmpty(selectedMeasureName)) {
            geoEngineInstance.getMapRenderer().setSelectedMeasureName(selectedMeasureName);
        }

        if ("TRUE".equalsIgnoreCase(isDocumentCompositionModeActive)) {
            setAttribute(DynamicPublisher.PUBLISHER_NAME, "SIMPLE_UI_PUBLISHER");
        } else {
            setAttribute(DynamicPublisher.PUBLISHER_NAME, "AJAX_UI_PUBLISHER");
        }

        String id = getAttributeAsString("SBI_EXECUTION_ID");
        setAttributeInSession(GEO_ENGINE_INSTANCE, geoEngineInstance);
    } catch (Exception e) {
        SpagoBIEngineStartupException serviceException = null;

        if (e instanceof SpagoBIEngineStartupException) {
            serviceException = (SpagoBIEngineStartupException) e;
        } else {
            Throwable rootException = e;
            while (rootException.getCause() != null) {
                rootException = rootException.getCause();
            }
            String str = rootException.getMessage() != null ? rootException.getMessage()
                    : rootException.getClass().getName();
            String message = "An unpredicted error occurred while executing " + getEngineName() + " service."
                    + "\nThe root cause of the error is: " + str;

            serviceException = new SpagoBIEngineStartupException(getEngineName(), message, e);
        }

        throw serviceException;
    } finally {
        if (hitsByExecutionContext != null)
            hitsByExecutionContext.stop();
        if (hitsByDocumentId != null)
            hitsByDocumentId.stop();
        if (hitsByUserId != null)
            hitsByUserId.stop();
        if (hitsByDate != null)
            hitsByDate.stop();
        if (hitsPrimary != null)
            hitsPrimary.stop();

    }

    // Put draw Map Action

    String outputFormat = null;
    File maptmpfile = null;
    boolean inlineResponse;
    String responseFileName;
    Monitor totalTimeMonitor = null;
    Monitor totalTimePerFormatMonitor = null;
    Monitor flushingResponseTotalTimeMonitor = null;
    Monitor errorHitsMonitor = null;

    logger.debug("IN");

    try {
        super.service(serviceRequest, serviceResponse);

        totalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.totalTime");

        //executionId = getAttributeAsString( "SBI_EXECUTION_ID" );

        outputFormat = getAttributeAsString(OUTPUT_FORMAT);
        logger.debug("Parameter [" + OUTPUT_FORMAT + "] is equal to [" + outputFormat + "]");

        inlineResponse = getAttributeAsBoolean(INLINE_RESPONSE, true);
        logger.debug("Parameter [" + INLINE_RESPONSE + "] is equal to [" + inlineResponse + "]");

        if (getAuditServiceProxy() != null)
            getAuditServiceProxy().notifyServiceStartEvent();

        IEngineInstance iEngInst = (IEngineInstance) getAttributeFromSession(EngineConstants.ENGINE_INSTANCE);
        GeoEngineInstance geoInstance = (GeoEngineInstance) iEngInst;

        if (outputFormat == null) {
            logger.info("Parameter [" + outputFormat + "] not specified into request");

            //outputFormat = (String)((GeoEngineInstance)).getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE);
            outputFormat = (String) geoInstance.getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE);
            logger.debug("Env Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] is equal to ["
                    + outputFormat + "]");
        }

        if (outputFormat == null) {
            logger.info(
                    "Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] not specified into environment");
            outputFormat = DEFAULT_OUTPUT_TYPE;
        }

        totalTimePerFormatMonitor = MonitorFactory
                .start("GeoEngine.drawMapAction." + outputFormat + "totalTime");

        try {
            if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) {
                maptmpfile = geoInstance.renderMap(GeoEngineConstants.JPEG);

            } else {
                maptmpfile = geoInstance.renderMap(outputFormat);
            }
        } catch (Throwable t) {
            throw new DrawMapServiceException(getActionName(), "Impossible to render map", t);
        }

        responseFileName = "map.svg";

        IStreamEncoder encoder = null;
        File tmpFile = null;
        if (outputFormat.equalsIgnoreCase(GeoEngineConstants.JPEG)) {
            encoder = new SVGMapConverter();
            responseFileName = "map.jpeg";
        } else if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) {

            encoder = new SVGMapConverter();
            BufferedInputStream bis = null;

            String dirS = System.getProperty("java.io.tmpdir");
            File imageFile = null;
            bis = new BufferedInputStream(new FileInputStream(maptmpfile));
            try {
                int contentLength = 0;
                int b = -1;
                String contentFileName = "tempJPEGExport";
                freezeHttpResponse();

                File dir = new File(dirS);
                imageFile = File.createTempFile("tempJPEGExport", ".jpeg", dir);
                FileOutputStream stream = new FileOutputStream(imageFile);

                encoder.encode(bis, stream);

                stream.flush();
                stream.close();

                File dirF = new File(dirS);
                tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF);
                Document pdfDocument = new Document();
                PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile));
                pdfDocument.open();
                Image jpg = Image.getInstance(imageFile.getPath());
                jpg.setRotation(new Double(Math.PI / 2).floatValue());
                jpg.scaleAbsolute(770, 520);
                pdfDocument.add(jpg);
                pdfDocument.close();
                docWriter.close();
                maptmpfile = tmpFile;

            } finally {
                bis.close();
                if (imageFile != null)
                    imageFile.delete();
            }

            responseFileName = "map.pdf";
            encoder = null;

        }

        try {
            flushingResponseTotalTimeMonitor = MonitorFactory
                    .start("GeoEngine.drawMapAction.flushResponse.totalTime");
            writeBackToClient(maptmpfile, encoder, inlineResponse, responseFileName,
                    getContentType(outputFormat));

        } catch (IOException e) {
            logger.error("error while flushing output", e);
            if (getAuditServiceProxy() != null)
                getAuditServiceProxy().notifyServiceErrorEvent("Error while flushing output");
            throw new DrawMapServiceException(getActionName(), "Error while flushing output", e);
        }

        if (getAuditServiceProxy() != null)
            getAuditServiceProxy().notifyServiceEndEvent();

        maptmpfile.delete();
        if (tmpFile != null)
            tmpFile.delete();

    } catch (Throwable t) {
        errorHitsMonitor = MonitorFactory.start("GeoEngine.errorHits");
        errorHitsMonitor.stop();
        DrawMapServiceException wrappedException;
        if (t instanceof DrawMapServiceException) {
            wrappedException = (DrawMapServiceException) t;
        } else {
            wrappedException = new DrawMapServiceException(getActionName(),
                    "An unpredicted error occurred while executing " + getActionName() + " service", t);
        }

        wrappedException.setDescription(wrappedException.getRootCause());
        Throwable rootException = wrappedException.getRootException();
        if (rootException instanceof SpagoBIEngineRuntimeException) {
            wrappedException.setHints(((SpagoBIEngineRuntimeException) rootException).getHints());
        }

        throw wrappedException;
    } finally {
        if (flushingResponseTotalTimeMonitor != null)
            flushingResponseTotalTimeMonitor.stop();
        if (totalTimePerFormatMonitor != null)
            totalTimePerFormatMonitor.stop();
        if (totalTimeMonitor != null)
            totalTimeMonitor.stop();

    }

    logger.debug("OUT");

    logger.debug("OUT");
}

From source file:it.govpay.web.console.pagamenti.gde.exporter.PdfExporter.java

License:Open Source License

public static void exportAsPdf(List<EventoBean> eventi, ByteArrayOutputStream baos,
        IEventiService eventiService) throws DocumentException, UtilsException {

    Document document = new Document();

    PdfWriter.getInstance(document, baos);

    document.open();/*from  w  ww.ja v a2 s.  c  om*/

    addMetaData(document);
    addTitlePage(document);

    // Start a new page
    document.newPage();

    addContent(document, eventi, eventiService);

    document.close();

}

From source file:it.prato.comune.tolomeo.web.TolomeoPrintPDFServlet.java

License:Open Source License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LogInterface logger = getLogger(request);

    String titolo = request.getParameter("titolo");
    String descrizione = request.getParameter("descrizione");
    String scala = request.getParameter("scala");
    String mapx = request.getParameter("mapx");
    String mapy = request.getParameter("mapy");
    //creo URL alla mappa
    URL urlMappa = new URL(URLDecoder.decode(request.getParameter("urlMappa"), "UTF-8"));
    URI uriMappa = null;//from  w w  w.ja  v  a2 s  .c  o  m
    try {
        uriMappa = new URI(urlMappa.getProtocol(), null, urlMappa.getHost(), urlMappa.getPort(),
                urlMappa.getPath(), urlMappa.getQuery() + "&mode=map&scale=" + scala + "&mapxy=" + mapx + "+"
                        + mapy + "&map_size=500 500",
                null);
        logger.info("URI di stampa mappa: " + uriMappa);
    } catch (URISyntaxException e) {
        logger.error("URI errore di sintassi", e);
    }

    Font BOLD15 = new Font(Font.HELVETICA, 15, Font.BOLD);
    Font FONT12 = new Font(Font.HELVETICA, 12, Font.NORMAL);
    Font FONT10 = new Font(Font.HELVETICA, 10, Font.NORMAL);

    Document doc = new Document();
    ;
    PdfWriter pdf = null;
    Paragraph par = new Paragraph();

    try {

        //creo il PDF
        response.setContentType("application/pdf");
        pdf = PdfWriter.getInstance(doc, response.getOutputStream());

        //attributi file
        doc.addTitle("Mappa di Prato");
        doc.addAuthor("Comune di Prato");
        doc.open();

        //intestazione
        par.setAlignment(Paragraph.ALIGN_CENTER);
        print("Comune di Prato", BOLD15, par, doc);
        print(titolo, FONT10, par, doc);
        print("", FONT10, par, doc);

        //mappa
        Image mappa = Image.getInstance(uriMappa.toURL());
        mappa.setAlignment(Image.MIDDLE);
        mappa.setBorder(Rectangle.BOX);
        mappa.setBorderWidth(1f);
        doc.add(mappa);

    } catch (Exception e) {
        logger.error("Errore durante la creazione del PDF", e);
        printErr(doc);
    } finally {
        doc.close();
        pdf.close();
        response.getOutputStream().close();
    }
}

From source file:javaaxp.xps2pdf.service.impl.PDFConverterImpl.java

License:Open Source License

@Override
public void covertToPDF(OutputStream ouput) throws XPSError {
    try {/* w w  w.  j a v a2 s .  c  om*/
        int firstPage = fPageController.getXPSAccess().getPageAccess(0).getFirstPageNum();
        int lastPage = fPageController.getXPSAccess().getPageAccess(0).getLastPageNum();

        Document document = new Document();
        document.setPageCount(lastPage - firstPage + 1);
        document.setPageSize(PageSize.LETTER);
        PdfWriter writer = PdfWriter.getInstance(document, ouput);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        for (int i = firstPage; i < 1; i++) {
            System.out.println("Converting page " + i);
            fPageController.setPage(i);
            PdfTemplate tp = cb.createTemplate((float) fPageController.getPage().getWidth(),
                    (float) fPageController.getPage().getHeight());
            Graphics g = tp.createGraphics((float) fPageController.getPage().getWidth(),
                    (float) fPageController.getPage().getHeight());
            JComponent toReturn = fPageViewer.getPageRenderer().getRendererComponent();
            toReturn.paint(g);
            cb.addTemplate(tp, 0, 0);
            document.newPage();
        }
        document.close();
    } catch (DocumentException e) {
        //rethrow
    }
}

From source file:jmemorize.core.io.PdfRtfBuilder.java

License:Open Source License

private static void export(Lesson lesson, int mode, File file) throws IOException {
    logger = Main.getLogger();/*from  ww  w .j  a  v a 2  s  .co  m*/

    FontFactory.registerDirectories();
    // set up the fonts we will use to write the front and back of cards
    String frontFontName = Settings.loadFont(FontType.CARD_FRONT).getFont().getFamily();
    frontFont = FontFactory.getFont(frontFontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

    if (frontFont == null) {
        logger.warning("FontFactory returned null (front) font for: " + frontFontName);
    }

    String backFontName = Settings.loadFont(FontType.CARD_FLIP).getFont().getFamily();
    backFont = FontFactory.getFont(backFontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

    if (backFont == null) {
        logger.warning("FontFactory returned null (back) font for: " + backFontName);
    }

    try {
        Document doc = new Document();
        OutputStream out = new FileOutputStream(file);

        switch (mode) {
        case PDF_MODE:
            PdfWriter.getInstance(doc, out);
            break;

        case RTF_MODE:
            RtfWriter2.getInstance(doc, out);
            break;
        }

        doc.setHeader(new HeaderFooter(new Phrase(file.getName()), false));
        doc.open();

        // add cards in subtrees
        List<Category> subtree = lesson.getRootCategory().getSubtreeList();
        for (Category category : subtree) {
            writeCategory(doc, category);
        }

        doc.close();

    } catch (Throwable t) {
        throw (IOException) new IOException("Could not export to PDF").initCause(t);
    }
}