Example usage for com.lowagie.text Document addTitle

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

Introduction

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

Prototype


public boolean addTitle(String title) 

Source Link

Document

Adds the title to a Document.

Usage

From source file:org.alchemy.core.AlcSession.java

License:Open Source License

/** Save the canvas to a single paged PDF file
 * //from  ww  w. j  a va  2  s.c o m
 * @param file  The file object to save the pdf to
 * @return      True if save worked, otherwise false
 */
boolean saveSinglePdf(File file) {
    // Get the current 'real' size of the canvas without margins/borders
    java.awt.Rectangle bounds = Alchemy.canvas.getVisibleRect();
    //int singlePdfWidth = Alchemy.window.getWindowSize().width;
    //int singlePdfHeight = Alchemy.window.getWindowSize().height;
    com.lowagie.text.Document document = new com.lowagie.text.Document(
            new com.lowagie.text.Rectangle(bounds.width, bounds.height), 0, 0, 0, 0);
    System.out.println("Save Single Pdf Called: " + file.toString());
    boolean noError = true;

    try {

        PdfWriter singleWriter = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addTitle("Alchemy Session");
        document.addAuthor(USER_NAME);
        document.addCreator("Alchemy <http://al.chemy.org>");

        // Add metadata and open the document
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XmpWriter xmp = new XmpWriter(os);
        PdfSchema pdf = new PdfSchema();
        pdf.setProperty(PdfSchema.KEYWORDS, "Alchemy <http://al.chemy.org>");
        //pdf.setProperty(PdfSchema.VERSION, "1.4");
        xmp.addRdfDescription(pdf);
        xmp.close();
        singleWriter.setXmpMetadata(os.toByteArray());

        // To avoid transparent colurs being converted from RGB>CMYK>RGB
        // We have to add everything to a transparency group
        PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
        transGroup.put(PdfName.CS, PdfName.DEVICERGB);

        document.open();

        PdfContentByte cb = singleWriter.getDirectContent();
        PdfTemplate tp = cb.createTemplate(bounds.width, bounds.height);

        document.newPage();

        cb.getPdfWriter().setGroup(transGroup);
        // Make sure the color space is Device RGB
        cb.setDefaultColorspace(PdfName.CS, PdfName.DEVICERGB);

        // Draw into the template and add it to the PDF 
        Graphics2D g2pdf = tp.createGraphics(bounds.width, bounds.height);
        Alchemy.canvas.setGuide(false);
        Alchemy.canvas.vectorCanvas.paintComponent(g2pdf);
        Alchemy.canvas.setGuide(true);
        g2pdf.dispose();
        cb.addTemplate(tp, 0, 0);

    } catch (DocumentException ex) {
        System.err.println(ex);
        noError = false;
    } catch (IOException ex) {
        System.err.println(ex);
        noError = false;
    }

    document.close();

    return noError;
}

From source file:org.alchemy.core.AlcSession.java

License:Open Source License

/** Adds a pdfReadPage to an existing pdf file
 * /* www  .  j  a v  a2  s. c  o  m*/
 * @param mainPdf   The main pdf with multiple pages.
 *                  Also used as the destination file.
 * @param tempPdf   The 'new' pdf with one pdfReadPage to be added to the main pdf
 * @return
 */
boolean addPageToPdf(File mainPdf, File tempPdf) {
    try {
        // Destination file created in the temp dir then we will move it
        File dest = new File(DIR_TEMP, "Alchemy.pdf");
        OutputStream output = new FileOutputStream(dest);

        PdfReader reader = new PdfReader(mainPdf.getPath());
        PdfReader newPdf = new PdfReader(tempPdf.getPath());

        // See if the size of the canvas has increased
        // Size of the most recent temp PDF
        com.lowagie.text.Rectangle currentSize = newPdf.getPageSizeWithRotation(1);
        // Size of the session pdf at present
        com.lowagie.text.Rectangle oldSize = reader.getPageSizeWithRotation(1);
        // Sizes to be used from now on
        float pdfWidth = oldSize.getWidth();
        float pdfHeight = oldSize.getHeight();
        if (currentSize.getWidth() > pdfWidth) {
            pdfWidth = currentSize.getWidth();
        }
        if (currentSize.getHeight() > pdfHeight) {
            pdfHeight = currentSize.getHeight();
        }

        // Use the new bigger canvas size if required
        com.lowagie.text.Document document = new com.lowagie.text.Document(
                new com.lowagie.text.Rectangle(pdfWidth, pdfHeight), 0, 0, 0, 0);
        PdfCopy copy = new PdfCopy(document, output);

        // Copy the meta data
        document.addTitle("Alchemy Session");
        document.addAuthor(USER_NAME);
        document.addCreator("Alchemy <http://al.chemy.org>");
        copy.setXmpMetadata(reader.getMetadata());
        document.open();

        // Holds the PDF
        PdfContentByte cb = copy.getDirectContent();

        // Add each page from the main PDF
        for (int i = 0; i < reader.getNumberOfPages();) {
            ++i;
            document.newPage();
            cb.setDefaultColorspace(PdfName.CS, PdfName.DEVICERGB);
            PdfImportedPage page = copy.getImportedPage(reader, i);
            copy.addPage(page);
        }
        // Add the last (new) page
        document.newPage();
        PdfImportedPage lastPage = copy.getImportedPage(newPdf, 1);
        copy.addPage(lastPage);
        output.flush();
        document.close();
        output.close();

        if (dest.exists()) {
            // Save the location of the main pdf
            String mainPdfPath = mainPdf.getPath();
            // Delete the old file
            if (mainPdf.exists()) {
                mainPdf.delete();
            }
            // The final joined up pdf file
            File joinPdf = new File(mainPdfPath);
            // Rename the file
            boolean success = dest.renameTo(joinPdf);
            if (!success) {
                System.err.println("Error moving Pdf");
                return false;
            }

        } else {
            System.err.println("File does not exist?!: " + dest.getAbsolutePath());
            return false;
        }
        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java

License:Open Source License

/**
 * construct a pdf document from pdf parts.
 * //from  w  w  w  . jav  a2 s.co m
 * @param files
 *            list containing the pdf to assemble
 * @param properties
 *            converter properties
 * @param fout
 *            outputstream to write the new pdf
 * @param base_url
 *            base url of the document
 * @param producer
 *            producer of the pdf
 * 
 * @throws CConvertException
 *             if an error occured while reconstruct.
 */
public static void reconstruct(final List files, final Map properties, final OutputStream fout,
        final String base_url, final String producer, final PageSize[] size, final List hf)
        throws CConvertException {
    OutputStream out = fout;
    OutputStream out2 = fout;
    boolean signed = false;
    OutputStream oldOut = null;
    File tmp = null;
    File tmp2 = null;
    try {
        tmp = File.createTempFile("yahp", "pdf");
        tmp2 = File.createTempFile("yahp", "pdf");
        oldOut = out;
        if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) {
            signed = true;
            out2 = new FileOutputStream(tmp2);
        } // end if
        else {
            out2 = oldOut;
        }
        out = new FileOutputStream(tmp);
        com.lowagie.text.Document document = null;
        PdfCopy writer = null;
        boolean first = true;

        Map mapSizeDoc = new HashMap();

        int totalPage = 0;

        for (int i = 0; i < files.size(); i++) {
            final File fPDF = (File) files.get(i);
            final PdfReader reader = new PdfReader(fPDF.getAbsolutePath());
            reader.consolidateNamedDestinations();

            final int n = reader.getNumberOfPages();

            if (first) {
                first = false;
                // step 1: creation of a document-object
                // set title/creator/author
                document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, out);
                // use pdf version 1.5
                writer.setPdfVersion(PdfWriter.VERSION_1_3);
                // compress the pdf
                writer.setFullCompression();

                // check if encryption is needed
                if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                    final String password = (String) properties
                            .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
                    final int securityType = CDocumentReconstructor.getSecurityFlags(properties);
                    writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType);
                } // end if

                final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE);

                if (title != null) {
                    document.addTitle(title);
                } // end if
                else if (base_url != null) {
                    document.addTitle(base_url);
                } // end else if

                final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR);

                if (creator != null) {
                    document.addCreator(creator);
                } // end if
                else {
                    document.addCreator(IHtmlToPdfTransformer.VERSION);
                } // end else

                final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR);

                if (author != null) {
                    document.addAuthor(author);
                } // end if

                final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER);

                if (sproducer != null) {
                    document.add(new Meta("Producer", sproducer));
                } // end if
                else {
                    document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION
                            + " - http://www.allcolor.org/YaHPConverter/ - " + producer)));
                } // end else

                // step 3: we open the document
                document.open();
            } // end if

            PdfImportedPage page;

            for (int j = 0; j < n;) {
                ++j;
                totalPage++;
                mapSizeDoc.put("" + totalPage, "" + i);
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
            } // end for
        } // end for

        document.close();
        out.flush();
        out.close();
        {
            final PdfReader reader = new PdfReader(tmp.getAbsolutePath());
            ;
            final int n = reader.getNumberOfPages();
            final PdfStamper stp = new PdfStamper(reader, out2);
            int i = 0;
            BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer();
            while (i < n) {
                i++;
                int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i));
                final int[] dsize = size[indexSize].getSize();
                final int[] dmargin = size[indexSize].getMargin();
                for (final Iterator it = hf.iterator(); it.hasNext();) {
                    final CHeaderFooter chf = (CHeaderFooter) it.next();
                    if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) {
                        continue;
                    } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) {
                        continue;
                    }
                    final String text = chf.getContent().replaceAll("<pagenumber>", "" + i)
                            .replaceAll("<pagecount>", "" + n);
                    // text over the existing page
                    final PdfContentByte over = stp.getOverContent(i);
                    final ByteArrayOutputStream bbout = new ByteArrayOutputStream();
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(),
                                properties, bbout);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url,
                                new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(),
                                properties, bbout);
                    }
                    final PdfReader readerHF = new PdfReader(bbout.toByteArray());
                    if (chf.getType().equals(CHeaderFooter.HEADER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]);
                    } else if (chf.getType().equals(CHeaderFooter.FOOTER)) {
                        over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0);
                    }
                    readerHF.close();
                }
            }
            stp.close();
        }
        try {
            out2.flush();
        } catch (Exception ignore) {
        } finally {
            try {
                out2.close();
            } catch (Exception ignore) {
            }
        }
        if (signed) {

            final String keypassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD);
            final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD);
            final String keyStorepassword = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD);
            final String privateKeyFile = (String) properties
                    .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE);
            final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON);
            final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION);
            final boolean selfSigned = !"false"
                    .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING));
            PdfReader reader = null;

            if (password != null) {
                reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes());
            } // end if
            else {
                reader = new PdfReader(tmp2.getAbsolutePath());
            } // end else

            final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType())
                    : KeyStore.getInstance("pkcs12");
            ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray());

            final String alias = (String) ks.aliases().nextElement();
            final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray());
            final Certificate chain[] = ks.getCertificateChain(alias);
            final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0');

            if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) {
                stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null,
                        CDocumentReconstructor.getSecurityFlags(properties));
            } // end if

            final PdfSignatureAppearance sap = stp.getSignatureAppearance();

            if (selfSigned) {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            } // end if
            else {
                sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            } // end else

            if (reason != null) {
                sap.setReason(reason);
            } // end if

            if (location != null) {
                sap.setLocation(location);
            } // end if

            stp.close();
            oldOut.flush();
        } // end if
    } // end try
    catch (final Exception e) {
        throw new CConvertException(
                "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e);
    } // end catch
    finally {
        try {
            tmp.delete();
        } // end try
        catch (final Exception ignore) {
        }
        try {
            tmp2.delete();
        } // end try
        catch (final Exception ignore) {
        }
    } // end finally
}

From source file:org.drools.verifier.doc.DroolsDocsBuilder.java

License:Apache License

public void writePDF(OutputStream out) {

    // TODO: Use i18n!

    Document document = new Document();

    try {/*from  w  w w.  j a va2s  . c  o  m*/
        PdfWriter.getInstance(document, out);

        HeaderFooter footer = DroolsDocsComponentFactory.createFooter(packageData.getName());

        document.setFooter(footer);

        document.addTitle(packageData.getName().toUpperCase());
        document.open();

        // First page, documentation info.            
        DroolsDocsComponentFactory.createFirstPage(document, currentDate, packageData);

        document.newPage();

        // List index of the rules            
        document.add(new Phrase("Table of Contents"));
        document.add(DroolsDocsComponentFactory.createContents(packageData.getRules()));

        document.newPage();

        for (DrlRuleParser ruleData : packageData.getRules()) {
            DroolsDocsComponentFactory.newRulePage(document, packageData.getName(), ruleData);
        }

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    }

    document.close();
}

From source file:org.freeeed.print.OfficePrint.java

License:Apache License

private void convertCSVToPdf(File officeDocFile, String originalFileName, File outputFile) {
    try {/*  w w  w.  ja  v a 2  s  .  c  om*/
        BufferedReader input = new BufferedReader(new FileReader(officeDocFile));
        Document document = new Document(PageSize.LETTER);
        PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();
        document.addSubject(originalFileName);
        document.addTitle(originalFileName);

        String line = "";
        while (null != (line = input.readLine())) {
            Paragraph p = new Paragraph(line);
            p.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(p);
        }
        document.close();
        input.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.gbif.ipt.task.Eml2Rtf.java

License:Apache License

/**
 * Construct RTF document, mainly out of information extracted from Resource's EML object. Currently, the decision
 * has been made to always do this in English.
 * /*from w w w.j  a va  2  s . co m*/
 * @param doc Document
 * @param resource Resource
 * @throws DocumentException if problem occurs during add
 */
public void writeEmlIntoRtf(Document doc, Resource resource, String lng) throws DocumentException {
    // initialising resourceBundle.
    Locale loc = new Locale(lng);
    resourceBundle = ResourceBundle.getBundle("ApplicationResources", loc);
    // this.action = action;
    Eml eml = resource.getEml();
    // configure page
    doc.setMargins(72, 72, 72, 72);
    System.out.println(DataDir.CONFIG_DIR);
    // write metadata
    doc.addAuthor(resource.getCreator().getName());
    doc.addCreationDate();
    doc.addTitle((eml.getTitle() == null) ? resource.getShortname() : eml.getTitle());
    // add the keywords to the document
    StringBuilder keys = new StringBuilder();
    for (KeywordSet kw : eml.getKeywords()) {
        if (keys.length() == 0) {
            keys.append(kw.getKeywordsString(", "));
        } else {
            keys.append(", " + kw.getKeywordsString(", "));
        }
    }
    String keysValue = keys.toString();
    doc.addKeywords(keysValue);
    // write proper doc
    doc.open();
    // title
    addPara(doc, eml.getTitle(), fontHeader, 0, Element.ALIGN_CENTER);
    doc.add(Chunk.NEWLINE);
    // Authors, affiliations and corresponging authors
    addAuthors(doc, eml);
    // Other various sections..
    addDates(doc);
    //addCitations(doc);
    // Section called "Resource Citation" above "Abstract"
    addResourceCitation(doc, eml);
    setResAbs(eml);
    setPalKey(keysValue);
    setDisAgr(eml);
    //addAbstract(doc, eml);
    addRes(doc);
    //addKeywords(doc, keysValue);
    addPalcla(doc);
    addAbs(doc);
    addKeyWord(doc);
    addGeneralDescription(doc, eml);
    addProjectData(doc, eml);
    //addResourceLink(doc, resource);
    addTaxonomicCoverages(doc, eml, loc);
    addSpatialCoverage(doc, eml);
    addTemporalCoverages(doc, eml, loc);
    addNaturalCollections(doc, eml);
    addMethods(doc, eml);
    addResul(doc);
    addDatasetDescriptions(doc, resource);
    //addMetadataDescriptions(doc, eml);
    addDiscu(doc);
    addAgrad(doc);
    addReferences(doc, eml);
    doc.close();
}

From source file:org.geomajas.plugin.print.document.SinglePageDocument.java

License:Open Source License

/**
 * Prepare the document before rendering.
 * //from  w  ww.j  a v  a 2s.c om
 * @param outputStream output stream to render to, null if only for layout
 * @param format format
 * @throws DocumentException oops
 * @throws IOException oops
 * @throws PrintException oops
 */
private void doRender(OutputStream outputStream, Format format)
        throws IOException, DocumentException, PrintException {
    // first render or re-render for different layout
    if (outputStream == null || baos == null || null != format) {
        if (baos == null) {
            baos = new ByteArrayOutputStream(); // let it grow as much as needed
        }
        baos.reset();
        boolean resize = false;
        if (page.getBounds().getWidth() == 0 || page.getBounds().getHeight() == 0) {
            resize = true;
        }
        // Create a document in the requested ISO scale.
        Document document = new Document(page.getBounds(), 0, 0, 0, 0);
        PdfWriter writer;
        writer = PdfWriter.getInstance(document, baos);

        // Render in correct colors for transparent rasters
        writer.setRgbTransparencyBlending(true);

        // The mapView is not scaled to the document, we assume the mapView
        // has the right ratio.

        // Write document title and metadata
        document.open();
        PdfContext context = new PdfContext(writer);
        context.initSize(page.getBounds());
        // first pass of all children to calculate size
        page.calculateSize(context);
        if (resize) {
            // we now know the bounds of the document
            // round 'm up and restart with a new document
            int width = (int) Math.ceil(page.getBounds().getWidth());
            int height = (int) Math.ceil(page.getBounds().getHeight());
            page.getConstraint().setWidth(width);
            page.getConstraint().setHeight(height);

            document = new Document(new Rectangle(width, height), 0, 0, 0, 0);
            writer = PdfWriter.getInstance(document, baos);
            // Render in correct colors for transparent rasters
            writer.setRgbTransparencyBlending(true);

            document.open();
            baos.reset();
            context = new PdfContext(writer);
            context.initSize(page.getBounds());
        }
        //int compressionLevel = writer.getCompressionLevel(); // For testing
        //writer.setCompressionLevel(0); 

        // Actual drawing
        document.addTitle("Geomajas");
        // second pass to layout
        page.layout(context);
        // finally render (uses baos)
        page.render(context);

        document.add(context.getImage());
        // Now close the document
        document.close();

        // convert to non-pdf format
        switch (format) {
        case PDF:
            break;
        case PNG:
        case JPG:

            BufferedImage bufferedImage = null;
            // Use JPedal lib for converting the PDF to PNG or JPG
            /** instance of PdfDecoder to convert PDF into image */
            PdfDecoder decodePdf = new PdfDecoder(true);

            /** set mappings for non-embedded fonts to use */
            PdfDecoder.setFontReplacements(decodePdf);
            decodePdf.useHiResScreenDisplay(true);
            decodePdf.getDPIFactory().setDpi(2 * 72);
            decodePdf.setPageParameters(1, 1);
            try {
                decodePdf.openPdfArray(baos.toByteArray());
                /** get page 1 as an image */
                bufferedImage = decodePdf.getPageAsImage(1);

                /** close the pdf file */
                decodePdf.closePdfFile();

            } catch (PdfException e) {
                throw new PrintException(e, PrintException.DOCUMENT_RENDER_PROBLEM);
            }

            baos.reset();

            // Update the DPI to  DPI_FOR_PNG_OUTPUT of bufferedImage, output written to baos

            final String formatName = format.getExtension();
            boolean convertedDPI = false;

            for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
                ImageWriter writer1 = iw.next();
                ImageWriteParam writeParam = writer1.getDefaultWriteParam();
                ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
                        .createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
                IIOMetadata metadata = writer1.getDefaultImageMetadata(typeSpecifier, writeParam);
                if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
                    continue;
                }

                setDPI(metadata);
                // Convert bufferedImage to baos
                final ImageOutputStream stream = ImageIO.createImageOutputStream(baos/*output*/);
                try {
                    writer1.setOutput(stream);
                    writer1.write(metadata,
                            new IIOImage(bufferedImage/*input*/, null/* No thumbnails*/, metadata), writeParam);
                    convertedDPI = true;
                } finally {
                    stream.flush();
                    stream.close();
                }
                break;
            }
            if (!convertedDPI) {
                baos.reset();
                //ImageIO.setUseCache(false);
                ImageIO.write(bufferedImage, format.getExtension(), baos);
            }
            break;
        default:
            throw new IllegalStateException(
                    "Oops, software error, need to support extra format at end of render" + format);
        }
        if (outputStream != null) {
            try {
                baos.writeTo(outputStream);
            } catch (IOException e) {
                throw e;
            }
        }
    } else {
        baos.writeTo(outputStream);
    }
}

From source file:org.geomajas.plugin.printing.document.SinglePageDocument.java

License:Open Source License

/**
 * Prepare the document before rendering.
 * /*www.  ja v a2 s.  c o m*/
 * @param outputStream output stream to render to, null if only for layout
 * @param format format
 * @throws DocumentException oops
 * @throws IOException oops
 * @throws PrintingException oops
 */
private void doRender(OutputStream outputStream, Format format)
        throws IOException, DocumentException, PrintingException {
    // first render or re-render for different layout
    if (outputStream == null || baos == null || null != format) {
        if (baos == null) {
            baos = new ByteArrayOutputStream(); // let it grow as much as needed
        }
        baos.reset();
        boolean resize = false;
        if (page.getBounds().getWidth() == 0 || page.getBounds().getHeight() == 0) {
            resize = true;
        }
        // Create a document in the requested ISO scale.
        Document document = new Document(page.getBounds(), 0, 0, 0, 0);
        PdfWriter writer;
        writer = PdfWriter.getInstance(document, baos);

        // Render in correct colors for transparent rasters
        writer.setRgbTransparencyBlending(true);

        // The mapView is not scaled to the document, we assume the mapView
        // has the right ratio.

        // Write document title and metadata
        document.open();
        PdfContext context = new PdfContext(writer);
        context.initSize(page.getBounds());
        // first pass of all children to calculate size
        page.calculateSize(context);
        if (resize) {
            // we now know the bounds of the document
            // round 'm up and restart with a new document
            int width = (int) Math.ceil(page.getBounds().getWidth());
            int height = (int) Math.ceil(page.getBounds().getHeight());
            page.getConstraint().setWidth(width);
            page.getConstraint().setHeight(height);

            document = new Document(new Rectangle(width, height), 0, 0, 0, 0);
            writer = PdfWriter.getInstance(document, baos);
            // Render in correct colors for transparent rasters
            writer.setRgbTransparencyBlending(true);

            document.open();
            baos.reset();
            context = new PdfContext(writer);
            context.initSize(page.getBounds());
        }
        //int compressionLevel = writer.getCompressionLevel(); // For testing
        //writer.setCompressionLevel(0); 

        // Actual drawing
        document.addTitle("Geomajas");
        // second pass to layout
        page.layout(context);
        // finally render (uses baos)
        page.render(context);

        document.add(context.getImage());
        // Now close the document
        document.close();

        // convert to non-pdf format
        switch (format) {
        case PDF:
            break;
        case PNG:
        case JPG:

            BufferedImage bufferedImage = null;
            // Use JPedal lib for converting the PDF to PNG or JPG
            /** instance of PdfDecoder to convert PDF into image */
            PdfDecoder decodePdf = new PdfDecoder(true);

            /** set mappings for non-embedded fonts to use */
            PdfDecoder.setFontReplacements(decodePdf);
            decodePdf.useHiResScreenDisplay(true);
            decodePdf.getDPIFactory().setDpi(2 * 72);
            decodePdf.setPageParameters(1, 1);
            try {
                decodePdf.openPdfArray(baos.toByteArray());
                /** get page 1 as an image */
                bufferedImage = decodePdf.getPageAsImage(1);

                /** close the pdf file */
                decodePdf.closePdfFile();

            } catch (PdfException e) {
                throw new PrintingException(e, PrintingException.DOCUMENT_RENDER_PROBLEM);
            }

            baos.reset();

            // Update the DPI to  DPI_FOR_PNG_OUTPUT of bufferedImage, output written to baos

            final String formatName = format.getExtension();
            boolean convertedDPI = false;

            for (Iterator<ImageWriter> iw = ImageIO.getImageWritersByFormatName(formatName); iw.hasNext();) {
                ImageWriter writer1 = iw.next();
                ImageWriteParam writeParam = writer1.getDefaultWriteParam();
                ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
                        .createFromBufferedImageType(BufferedImage.TYPE_INT_ARGB);
                IIOMetadata metadata = writer1.getDefaultImageMetadata(typeSpecifier, writeParam);
                if (metadata.isReadOnly() || !metadata.isStandardMetadataFormatSupported()) {
                    continue;
                }

                setDPI(metadata);
                // Convert bufferedImage to baos
                final ImageOutputStream stream = ImageIO.createImageOutputStream(baos/*output*/);
                try {
                    writer1.setOutput(stream);
                    writer1.write(metadata,
                            new IIOImage(bufferedImage/*input*/, null/* No thumbnails*/, metadata), writeParam);
                    convertedDPI = true;
                } finally {
                    stream.flush();
                    stream.close();
                }
                break;
            }
            if (!convertedDPI) {
                baos.reset();
                //ImageIO.setUseCache(false);
                ImageIO.write(bufferedImage, format.getExtension(), baos);
            }
            break;
        default:
            throw new IllegalStateException(
                    "Oops, software error, need to support extra format at end of render" + format);
        }
        if (outputStream != null) {
            try {
                baos.writeTo(outputStream);
            } catch (IOException e) {
                throw e;
            }
        }
    } else {
        baos.writeTo(outputStream);
    }
}

From source file:org.gtdfree.addons.PDFExportAddOn.java

License:Open Source License

@Override
public void export(GTDModel model, ActionsCollection collection, OutputStream out,
        ExportAddOn.ExportOrder order, FileFilter ff, boolean compact) throws Exception {

    fontSelector = new FontSelector();
    fontSelectorB = new FontSelector();
    fontSelectorB2 = new FontSelector();
    fontSelectorB4 = new FontSelector();

    baseFont = fontModel.getBaseFont();/*from w  w  w  . j  a  v a2 s.c  o  m*/

    for (BaseFont bf : fontModel.getFonts()) {
        fontSelector.addFont(new Font(bf, baseFontSize));
        fontSelectorB.addFont(new Font(bf, baseFontSize, Font.BOLD));
        fontSelectorB2.addFont(new Font(bf, baseFontSize + 2, Font.BOLD));
        fontSelectorB4.addFont(new Font(bf, baseFontSize + 4, Font.BOLD));
    }

    boolean emptyH2 = false;
    boolean emptyH3 = false;

    PdfPTable actionTable = null;

    Document doc = new Document();

    if (sizeSet) {
        doc.setPageSize(pageSize);
    }
    if (marginSet) {
        doc.setMargins(marginLeft, marginRight, marginTop, marginBottom);
    }

    //System.out.println("PDF size "+doc.getPageSize().toString());
    //System.out.println("PDF m "+marginLeft+" "+marginRight+" "+marginTop+" "+marginBottom);

    @SuppressWarnings("unused")
    PdfWriter pw = PdfWriter.getInstance(doc, out);

    doc.addCreationDate();
    doc.addTitle("GTD-Free PDF");
    doc.addSubject("GTD-Free data exported as PDF");

    HeaderFooter footer = new HeaderFooter(newParagraph(), true);
    footer.setAlignment(HeaderFooter.ALIGN_CENTER);
    footer.setBorder(HeaderFooter.TOP);
    doc.setFooter(footer);

    doc.open();

    Phrase ch = newTitle("GTD-Free Data");
    Paragraph p = new Paragraph(ch);
    p.setAlignment(Paragraph.ALIGN_CENTER);

    PdfPTable t = new PdfPTable(1);
    t.setWidthPercentage(100f);
    PdfPCell c = newCell(p);
    c.setBorder(Table.BOTTOM);
    c.setBorderWidth(2.5f);
    c.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
    c.setPadding(5f);
    t.addCell(c);
    doc.add(t);

    Iterator<Object> it = collection.iterator(order);

    while (it.hasNext()) {
        Object o = it.next();

        if (o == ActionsCollection.ACTIONS_WITHOUT_PROJECT) {

            if (order == ExportAddOn.ExportOrder.FoldersProjectsActions) {

                doc.add(newSubSection(ActionsCollection.ACTIONS_WITHOUT_PROJECT));

                emptyH2 = false;
                emptyH3 = true;
            } else {

                doc.add(newSection(ActionsCollection.ACTIONS_WITHOUT_PROJECT));

                emptyH2 = true;
                emptyH3 = false;
            }

            continue;
        }

        if (o instanceof Folder) {

            Folder f = (Folder) o;

            if (actionTable != null) {
                doc.add(actionTable);
                actionTable = null;
            }

            if (f.isProject()) {

                if (order == ExportAddOn.ExportOrder.ProjectsActions
                        || order == ExportAddOn.ExportOrder.ProjectsFoldersActions) {

                    if (emptyH2 || emptyH3) {
                        p = newParagraph(NONE_DOT);
                        doc.add(p);
                    }

                    doc.add(newSection(f.getName()));

                    if (compact) {
                        if (f.getDescription() != null && f.getDescription().length() > 0) {
                            p = newParagraph(f.getDescription());
                            p.setIndentationLeft(10f);
                            p.setIndentationRight(10f);
                            doc.add(p);
                        }
                    } else {
                        t = new PdfPTable(2);
                        t.setKeepTogether(true);
                        t.setSpacingBefore(5f);
                        t.setWidthPercentage(66f);
                        t.setWidths(new float[] { 0.33f, 0.66f });

                        c = newCell("ID");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.getId())));
                        t.addCell(c);
                        c = newCell("Type");
                        t.addCell(c);
                        c = newCell(newStrongParagraph("Project"));
                        t.addCell(c);
                        c = newCell("Open");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.getOpenCount())));
                        t.addCell(c);
                        c = newCell("All");
                        t.addCell(c);
                        c = newCell(newStrongParagraph(String.valueOf(f.size())));
                        t.addCell(c);
                        c = newCell("Description");
                        t.addCell(c);
                        c = newDescriptionCell(f.getDescription());
                        t.addCell(c);

                        doc.add(t);
                    }

                    emptyH2 = true;
                    emptyH3 = false;

                } else {

                    if (emptyH3) {
                        p = newParagraph(NONE_DOT);
                        doc.add(p);
                    }

                    doc.add(newSubSection("Project:" + " " + f.getName()));

                    emptyH2 = false;
                    emptyH3 = true;
                }

                continue;

            }
            if (order == ExportAddOn.ExportOrder.FoldersActions
                    || order == ExportAddOn.ExportOrder.FoldersProjectsActions) {

                if (emptyH2 || emptyH3) {
                    p = newParagraph(NONE_DOT);
                    doc.add(p);
                }

                doc.add(newSection(f.getName()));

                if (compact) {
                    if (f.getDescription() != null && f.getDescription().length() > 0) {
                        p = newParagraph(f.getDescription());
                        p.setIndentationLeft(10f);
                        p.setIndentationRight(10f);
                        doc.add(p);
                    }
                } else {

                    t = new PdfPTable(2);
                    t.setKeepTogether(true);
                    t.setSpacingBefore(5f);
                    t.setWidthPercentage(66f);
                    t.setWidths(new float[] { 0.33f, 0.66f });

                    c = newCell("ID");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.getId())));
                    t.addCell(c);

                    String type = "";
                    if (f.isAction()) {
                        type = "Action list";
                    } else if (f.isInBucket()) {
                        type = "In-Bucket";
                    } else if (f.isQueue()) {
                        type = "Next action queue";
                    } else if (f.isReference()) {
                        type = "Reference list";
                    } else if (f.isSomeday()) {
                        type = "Someday/Maybe list";
                    } else if (f.isBuildIn()) {
                        type = "Default list";
                    }

                    c = newCell("Type");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(type));
                    t.addCell(c);
                    c = newCell("Open");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.getOpenCount())));
                    t.addCell(c);
                    c = newCell("All");
                    t.addCell(c);
                    c = newCell(newStrongParagraph(String.valueOf(f.size())));
                    t.addCell(c);
                    c = newCell("Description");
                    t.addCell(c);
                    c = newDescriptionCell(f.getDescription());
                    t.addCell(c);

                    doc.add(t);
                }

                emptyH2 = true;
                emptyH3 = false;

            } else {

                if (emptyH3) {
                    p = newParagraph(NONE_DOT);
                    doc.add(p);
                }

                doc.add(newSubSection("List:" + " " + f.getName()));

                emptyH2 = false;
                emptyH3 = true;

            }

            continue;

        }

        if (o instanceof Action) {
            emptyH2 = false;
            emptyH3 = false;

            Action a = (Action) o;

            if (compact) {

                if (actionTable == null) {
                    actionTable = new PdfPTable(5);
                    actionTable.setWidthPercentage(100f);
                    actionTable.setHeaderRows(1);
                    actionTable.setSpacingBefore(5f);
                    c = newHeaderCell("ID");
                    actionTable.addCell(c);
                    c = newHeaderCell("Pri.");
                    actionTable.addCell(c);
                    c = newHeaderCell("Description");
                    actionTable.addCell(c);
                    c = newHeaderCell("Reminder");
                    actionTable.addCell(c);
                    c = newHeaderCell(CHECK_RESOLVED);
                    actionTable.addCell(c);

                    float width = doc.getPageSize().getWidth() - doc.getPageSize().getBorderWidthLeft()
                            - doc.getPageSize().getBorderWidthRight();
                    int i = model.getLastActionID();
                    float step = baseFontSize - 1;
                    int steps = (int) Math.floor(Math.log10(i)) + 1;
                    // ID column
                    float col1 = 8 + steps * step;
                    // Priority column
                    float col2 = 4 + 3 * (baseFontSize + 4);
                    // Reminder column
                    float col4 = 10 + step * 11;
                    // Resolved column
                    float col5 = 8 + baseFontSize;
                    // Description column
                    float col3 = width - col1 - col2 - col4 - col5;
                    actionTable.setWidths(new float[] { col1, col2, col3, col4, col5 });

                }

                addSingleActionRow(a, actionTable);

            } else {
                addSingleActionTable(model, doc, a);
            }
        }

    }

    if (actionTable != null) {
        doc.add(actionTable);
        actionTable = null;
    }
    if (emptyH2 || emptyH3) {

        p = newParagraph(NONE_DOT);
        doc.add(p);
    }

    //w.writeCharacters("Exported: "+ApplicationHelper.toISODateTimeString(new Date()));

    doc.close();
}

From source file:org.inbio.modeling.core.manager.impl.ExportManagerImpl.java

License:Open Source License

private void addMetadata(Document d) {

    // Add metadata
    d.addTitle(this.getI18nString("pdfReport.metadataTitle"));
    d.addSubject(this.getI18nString("pdfReport.metadataSubject"));
    d.addKeywords(this.getI18nString("pdfReport.metadataKeywords"));
    d.addCreator(this.getI18nString("pdfReport.metadataCreator"));
}