Example usage for com.lowagie.text.pdf PdfWriter getInstance

List of usage examples for com.lowagie.text.pdf PdfWriter getInstance

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter getInstance.

Prototype


public static PdfWriter getInstance(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Use this method to get an instance of the PdfWriter.

Usage

From source file:net.laubenberger.wichtel.helper.HelperPdf.java

License:Open Source License

/**
 * Writes a PDF from multiple image files to a {@link File}.
 * /* w  ww .  j a  va  2  s.c  o m*/
 * @param pageSize
 *           of the PDF
 * @param scale
 *           images to fit the page size
 * @param file
 *           output as PDF
 * @param files
 *           for the PDF
 * @throws DocumentException
 * @throws IOException
 * @see File
 * @see Rectangle
 * @since 0.0.1
 */
public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file,
        final File... files) throws DocumentException, IOException { // $JUnit$
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodStart(pageSize, scale, file, files));
    if (null == pageSize) {
        throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$
    }
    if (null == file) {
        throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$
    }
    if (null == files) {
        throw new RuntimeExceptionIsNull("files"); //$NON-NLS-1$
    }
    if (!HelperArray.isValid(files)) {
        throw new RuntimeExceptionIsEmpty("files"); //$NON-NLS-1$
    }

    final Document document = new Document(pageSize);
    document.setMargins(0.0F, 0.0F, 0.0F, 0.0F);

    try (FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) {
        PdfWriter.getInstance(document, fos);
        document.open();

        for (final File inputFile : files) {
            if (null == inputFile) {
                throw new RuntimeExceptionIsNull("inputFile"); //$NON-NLS-1$
            }
            final Image image = Image.getInstance(inputFile.getAbsolutePath());

            if (scale) {
                image.scaleToFit(pageSize.getWidth(), pageSize.getHeight());
            }
            document.add(image);
            document.newPage();
        }

        document.close();
    }
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodExit());
}

From source file:net.laubenberger.wichtel.helper.HelperPdf.java

License:Open Source License

/**
 * Writes a PDF from multiple {@link java.awt.Image} to a {@link File}.
 * /*w w  w  .jav a 2s.  com*/
 * @param pageSize
 *           of the PDF
 * @param scale
 *           images to fit the page size
 * @param file
 *           output as PDF
 * @param images
 *           for the PDF
 * @throws DocumentException
 * @throws IOException
 * @see File
 * @see java.awt.Image
 * @see Rectangle
 * @since 0.0.1
 */
public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file,
        final java.awt.Image... images) throws DocumentException, IOException { // $JUnit$
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodStart(pageSize, scale, file, images));
    if (null == pageSize) {
        throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$
    }
    if (null == file) {
        throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$
    }
    if (null == images) {
        throw new RuntimeExceptionIsNull("images"); //$NON-NLS-1$
    }
    if (!HelperArray.isValid(images)) {
        throw new RuntimeExceptionIsEmpty("images"); //$NON-NLS-1$
    }

    final Document document = new Document(pageSize);
    document.setMargins(0.0F, 0.0F, 0.0F, 0.0F);

    try (FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) {
        PdfWriter.getInstance(document, fos);
        document.open();

        for (final java.awt.Image tempImage : images) {
            if (null == tempImage) {
                throw new RuntimeExceptionIsNull("tempImage"); //$NON-NLS-1$
            }
            final Image image = Image.getInstance(tempImage, null);

            if (scale) {
                image.scaleToFit(pageSize.getWidth(), pageSize.getHeight());
            }
            document.add(image);
            document.newPage();
        }
    }
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodExit());
}

From source file:net.mitnet.tools.pdf.book.pdf.builder.PdfBookBuilder.java

License:Open Source License

public void buildBook(List<File> inputFileList, File outputFile) {

    try {/*from w  w w.j  a v  a  2s . co m*/

        float pageWidth = getConfig().getPageWidth();
        float pageHeight = getConfig().getPageHeight();

        // Create new Document

        /*
        float marginLeft = 36;
        float marginRight = 36;
        float marginTop = 36;
        float marginBottom = 36;
        */

        if (isVerboseEnabled()) {
            verbose("Building output PDF file " + outputFile);
        }

        // TableOfContents toc = new TableOfContents();

        ProgressMonitor progressMonitor = getConfig().getProgressMonitor();
        TocRowChangeListener tocRowChangeListener = getConfig().getTocRowChangeListener();

        Document outputDocument = new Document(getConfig().getPageSize());
        // Document outputDocument = new Document( getPageSize(), marginLeft, marginRight, marginTop, marginBottom );

        PdfWriter pdfWriter = PdfWriter.getInstance(outputDocument, new FileOutputStream(outputFile));

        // TODO - review PDF page event forwarder
        PdfPageEventLogger pdfPageEventLogger = new PdfPageEventLogger();
        pdfWriter.setPageEvent(pdfPageEventLogger);

        outputDocument.open();

        String metaTitle = getConfig().getMetaTitle();
        if (!StringUtils.isEmpty(metaTitle)) {
            outputDocument.addTitle(metaTitle);
        }
        String metaAuthor = getConfig().getMetaAuthor();
        if (!StringUtils.isEmpty(metaAuthor)) {
            outputDocument.addAuthor(metaAuthor);
        }

        PdfContentByte pdfContent = pdfWriter.getDirectContent();

        // Loop through and pull pages
        int outputPageCount = 0;
        int currentSourceFileIndex = 0;
        int maxSourceFileIndex = inputFileList.size();

        // BaseFont pageLabelFont = BaseFont.createFont( PdfBookBuilderConfig.DEFAULT_FONT, BaseFont.CP1250, BaseFont.EMBEDDED );
        BaseFont pageLabelFont = BaseFont.createFont(PdfBookBuilderConfig.DEFAULT_FONT_PATH, BaseFont.CP1250,
                BaseFont.EMBEDDED);
        if (isVerboseEnabled()) {
            verbose("Using page label font " + pageLabelFont);
        }

        if (isVerboseEnabled()) {
            verbose("Assembling pages using n-up " + getConfig().getNup());
        }

        for (File sourceFile : inputFileList) {

            currentSourceFileIndex++;

            // TODO - refactor current file PDF page processing to another method
            // TODO - handle failover to ensure processing continues ???

            if (sourceFile.isFile()) {

                if (isVerboseEnabled()) {
                    verbose("Reading source PDF file " + sourceFile);
                }

                int sourcePageIndex = 0;

                PdfReader sourcePdfReader = new PdfReader(sourceFile.getCanonicalPath());
                PdfReaderHelper sourcePdfReaderHelper = new PdfReaderHelper(sourcePdfReader);
                if (isVerboseEnabled()) {
                    verbose("PDF reader is " + sourcePdfReader);
                    verbose("PDF reader helper is " + sourcePdfReaderHelper);
                }

                String currentSourcePdfTitle = FilenameUtils.getBaseName(sourceFile.getName());
                String currentSourcePdfAuthor = getSystemUserName();
                if (isVerboseEnabled()) {
                    verbose("PDF title is " + currentSourcePdfTitle);
                    verbose("PDF author is " + currentSourcePdfAuthor);
                }

                currentSourcePdfTitle = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfTitle);
                currentSourcePdfAuthor = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfAuthor);
                if (isVerboseEnabled()) {
                    verbose("PDF info title is " + currentSourcePdfTitle);
                    verbose("PDF info author is " + currentSourcePdfAuthor);
                }

                boolean firstPageOfCurrentSource = true;

                int maxSourcePages = sourcePdfReader.getNumberOfPages();
                if (isVerboseEnabled()) {
                    verbose("There are " + maxSourcePages + " page(s) in source PDF file " + sourceFile);
                }

                // process all pages from source doc
                while (sourcePageIndex < maxSourcePages) {

                    // add new page to current document
                    outputDocument.newPage();

                    outputPageCount++;
                    if (isVerboseEnabled()) {
                        verbose("Building output PDF page " + outputPageCount + " ...");
                    }

                    // add first page of current source to TOC listener
                    if (firstPageOfCurrentSource) {
                        int currentPageIndex = outputPageCount;
                        if (tocRowChangeListener != null) {
                            TocRow tocEntry = new TocRow(currentSourcePdfTitle, currentPageIndex);
                            tocRowChangeListener.addTocRow(tocEntry);
                            if (isVerboseEnabled()) {
                                verbose("Added TOC entry " + tocEntry + " to listener");
                            }
                        }
                        firstPageOfCurrentSource = false;
                    }

                    // extract first page from source document
                    sourcePageIndex++;
                    if (isVerboseEnabled()) {
                        verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                + " from source to output");
                    }
                    PdfImportedPage page1 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);

                    // n-up is 1
                    if (config.getNup() == 1) {
                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        // TODO - calculate scaling/transform based on page rect and template rect
                        float p1a = 0.65f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.65f;
                        float p1e = 20;
                        float p1f = 160;
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // n-up is 2 (default)
                    } else {

                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        float p1a = 0.5f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.5f;
                        float p1e = (125);
                        float p1f = ((pageWidth / 2) + 120 + 20);
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // extract second page from source document ?
                        PdfImportedPage page2 = null;
                        if (sourcePageIndex < maxSourcePages) {
                            sourcePageIndex++;
                            if (isVerboseEnabled()) {
                                verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                        + " from source to output");
                            }
                            page2 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);
                        }

                        // add second page to bottom half of current page
                        if (page2 != null) {
                            // TODO - review magic transformation matrix numbers and offsets
                            float p2a = 0.5f;
                            float p2b = 0;
                            float p2c = 0;
                            float p2d = 0.5f;
                            float p2e = 125;
                            float p2f = 120;
                            pdfContent.addTemplate(page2, p2a, p2b, p2c, p2d, p2e, p2f);
                        }
                    }

                    /*
                    // add first page to top half of current page
                    // TODO - review magic transformation matrix numbers and offsets
                    float p1a = 0.5f;
                    float p1b = 0;
                    float p1c = 0;
                    float p1d = 0.5f;
                    float p1e = (125);
                    float p1f = ((pageWidth / 2) + 120 + 20);
                    pdfContent.addTemplate( page1, p1a, p1b, p1c, p1d, p1e, p1f );
                            
                    // add second page to bottom half of current page
                    if (page2 != null) {
                       // TODO - review magic transformation matrix numbers and offsets
                       float p2a = 0.5f; 
                       float p2b = 0;
                       float p2c = 0;
                       float p2d = 0.5f;
                       float p2e = 125;
                       float p2f = 120;
                       pdfContent.addTemplate( page2, p2a, p2b, p2c, p2d, p2e, p2f );
                    }
                    */

                    // Add current page number to page footer
                    String pageCountLabel = "Page " + outputPageCount;
                    pdfContent.beginText();
                    pdfContent.setFontAndSize(pageLabelFont, PdfBookBuilderConfig.DEFAULT_FONT_SIZE);
                    pdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, pageCountLabel, (pageWidth / 2), 40,
                            0);
                    pdfContent.endText();
                }

                if (isVerboseEnabled()) {
                    verbose("Finished reading " + maxSourcePages + " page(s) from source PDF file "
                            + sourceFile);
                }

                // update progress
                if (isVerboseEnabled()) {
                    if (progressMonitor != null) {
                        int fileProgressPercentage = MathHelper.calculatePercentage(currentSourceFileIndex,
                                maxSourceFileIndex);
                        progressMonitor.setProgressPercentage(fileProgressPercentage);
                    }
                }
            }
        }

        // close document
        outputDocument.close();

        if (isVerboseEnabled()) {
            verbose("Output PDF file " + outputFile + " contains " + outputPageCount + " page(s)");
        }

        // TODO - output ODT page stats summary

    } catch (Exception e) {

        String msg = "Error building PDF book: " + e.getMessage();
        e.printStackTrace(System.err);
        System.err.println(msg);

    }

}

From source file:net.nosleep.superanalyzer.Share.java

License:Open Source License

public static void saveAnalysisPdf(JFrame window, Analysis analysis, JProgressBar progressBar) {

    File pdfFile = askForFile(window, "pdf");
    if (pdfFile == null)
        return;//from  w w w. j  a  v a2  s  .  c  om

    Misc.printMemoryInfo("pdfstart");

    DateFormat dateFormat = new SimpleDateFormat().getDateInstance(DateFormat.SHORT);
    String infoString = Misc.getString("CREATED_ON") + " "
            + dateFormat.format(Calendar.getInstance().getTime());

    int viewCount = 15;
    int viewsDone = 0;

    progressBar.setMinimum(0);
    progressBar.setMaximum(viewCount);

    Dimension d = new Dimension(500, 400);

    try {

        String tmpPath = System.getProperty("java.io.tmpdir") + "/image.png";

        // create the pdf document object
        Document document = new Document();

        // create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(pdfFile));

        // we open the document
        document.open();

        Font titleFont = FontFactory.getFont(FontFactory.HELVETICA, 18, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));

        Paragraph p = new Paragraph(Misc.getString("MY_MUSIC_COLLECTION"), titleFont);
        p.setSpacingAfter(4);
        document.add(p);

        Font subtitleFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x88, 0x88, 0x88));

        p = new Paragraph("The Super Analyzer by Nosleep Software", subtitleFont);
        p.setSpacingAfter(-2);
        document.add(p);

        p = new Paragraph(infoString, subtitleFont);
        p.setSpacingAfter(30);
        document.add(p);

        PdfPTable table = new PdfPTable(2);
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
        table.setTotalWidth(500f);
        table.setLockedWidth(true);

        Font statNameFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x66, 0x66, 0x66));

        Font statValueFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));

        Vector<StringTriple> statPairs = SummaryView.createStatPairs(analysis);
        Paragraph statParagraph = new Paragraph();

        Font summaryTitleFont = FontFactory.getFont(FontFactory.HELVETICA, 11, Font.BOLD,
                new Color(0x00, 0x00, 0x00));
        Paragraph titleParagraph = new Paragraph(Misc.getString("SUMMARY"), summaryTitleFont);
        statParagraph.add(titleParagraph);

        Paragraph spaceParagraph = new Paragraph("", statNameFont);
        statParagraph.add(spaceParagraph);

        for (int i = 0; i < statPairs.size(); i++) {
            Paragraph statLine = new Paragraph();
            StringTriple triple = statPairs.elementAt(i);
            Phrase namePhrase = new Phrase(triple.Name + ": ", statNameFont);
            Phrase valuePhrase = new Phrase(triple.Value, statValueFont);
            statLine.add(namePhrase);
            statLine.add(valuePhrase);
            statParagraph.add(statLine);
        }
        table.addCell(statParagraph);

        viewsDone++;
        progressBar.setValue(viewsDone);

        GenreView genreView = new GenreView(analysis);
        genreView.saveImage(new File(tmpPath), d);
        genreView = null;

        Image img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        LikesView likesView = new LikesView(analysis);
        likesView.saveImage(new File(tmpPath), d);
        likesView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        YearView yearView = new YearView(analysis);
        yearView.saveImage(new File(tmpPath), d);
        yearView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        RatingView ratingView = new RatingView(analysis);
        ratingView.saveImage(new File(tmpPath), d);
        ratingView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        TimeView timeView = new TimeView(analysis);
        timeView.saveImage(new File(tmpPath), d);
        timeView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        QualityView qualityView = new QualityView(analysis);
        qualityView.saveImage(new File(tmpPath), d);
        qualityView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        PlayCountView playCountView = new PlayCountView(analysis);
        playCountView.saveImage(new File(tmpPath), d);
        playCountView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        MostPlayedAAView mostPlayedAAView = new MostPlayedAAView(analysis);

        mostPlayedAAView.saveImage(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedAAView.saveImageExtra(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedAAView = null;

        viewsDone++;
        progressBar.setValue(viewsDone);

        MostPlayedDGView mostPlayedDGView = new MostPlayedDGView(analysis);

        mostPlayedDGView.saveImage(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedDGView.saveImageExtra(new File(tmpPath), d);
        img = Image.getInstance(tmpPath);
        table.addCell(img);

        mostPlayedDGView = null;

        viewsDone++;
        progressBar.setValue(viewsDone);

        EncodingKindView encodingKindView = new EncodingKindView(analysis);
        encodingKindView.saveImage(new File(tmpPath), d);
        encodingKindView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        GrowthView growthView = new GrowthView(analysis);
        growthView.saveImage(new File(tmpPath), d);
        growthView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        viewsDone++;
        progressBar.setValue(viewsDone);

        WordView wordView = new WordView(analysis);
        wordView.saveImage(new File(tmpPath), d);
        wordView = null;

        img = Image.getInstance(tmpPath);
        table.addCell(img);

        table.addCell("");

        viewsDone++;
        progressBar.setValue(viewsDone);
        Misc.printMemoryInfo("pdfend");

        document.add(table);

        // step 5: we close the document
        document.close();

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

From source file:net.nosleep.superanalyzer.Share.java

License:Open Source License

public static void saveListOfAlbumsAsPdf(JFrame window, Analysis analysis, JProgressBar progressBar) {
    File file = askForFile(window, "pdf");
    if (file == null)
        return;/*w  ww. j  av a  2s. co  m*/

    Hashtable albums = analysis.getHash(Analysis.KIND_ALBUM);

    DecimalFormat timeFormat = new DecimalFormat("0.0");

    StringPair list[] = new StringPair[albums.size()];
    Enumeration keys = albums.keys();
    Integer index = 0;
    String regex = Album.SeparatorRegEx;
    while (keys.hasMoreElements()) {
        String albumartist = (String) keys.nextElement();
        String[] parts = albumartist.split(regex);
        StringPair pair = new StringPair(parts[1], parts[0]);
        list[index] = pair;
        index++;
    }

    Arrays.sort(list, new StringPairComparator());

    int done = 0;
    progressBar.setMinimum(0);
    progressBar.setMaximum(list.length);

    String infoString = NumberFormat.getInstance().format(list.length) + " ";
    if (list.length == 1)
        infoString += Misc.getString("ALBUM") + ", ";
    else
        infoString += Misc.getString("ALBUMS") + ", ";
    DateFormat dateFormat = new SimpleDateFormat().getDateInstance(DateFormat.SHORT);
    infoString += "created on " + dateFormat.format(Calendar.getInstance().getTime());

    try {
        String tmpPath = System.getProperty("java.io.tmpdir") + "/image.png";

        // create the pdf document object
        Document document = new Document();

        // create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.getInstance(document, new FileOutputStream(file));

        // we open the document
        document.open();

        Font titleFont = FontFactory.getFont(FontFactory.HELVETICA, 18, Font.NORMAL,
                new Color(0x00, 0x00, 0x00));
        Paragraph p = new Paragraph(Misc.getString("MY_ALBUMS"), titleFont);
        p.setSpacingAfter(4);
        document.add(p);

        Font subtitleFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL,
                new Color(0x88, 0x88, 0x88));
        p = new Paragraph("The Super Analyzer by Nosleep Software", subtitleFont);
        p.setSpacingAfter(-2);
        document.add(p);

        p = new Paragraph(infoString, subtitleFont);
        p.setSpacingAfter(30);
        document.add(p);

        FontSelector albumSelector = new FontSelector();
        Color albumColor = new Color(0x55, 0x55, 0x55);
        albumSelector.addFont(FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, albumColor));
        Font albumAsianFont = FontFactory.getFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
        albumAsianFont.setSize(8);
        albumAsianFont.setColor(albumColor);
        albumSelector.addFont(albumAsianFont);

        FontSelector artistSelector = new FontSelector();
        Color artistColor = new Color(0x77, 0x77, 0x77);
        artistSelector.addFont(FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, artistColor));
        Font artistAsianFont = FontFactory.getFont("MSung-Light", "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
        artistAsianFont.setSize(8);
        artistAsianFont.setColor(artistColor);
        artistSelector.addFont(artistAsianFont);

        for (index = 0; index < list.length; index++) {
            p = new Paragraph();
            p.setLeading(9);

            // separate the string into the album and artist parts

            Phrase phrase = albumSelector.process(list[index].Value);
            p.add(phrase);

            phrase = artistSelector.process(" " + Misc.getString("BY") + " " + list[index].Name);
            p.add(phrase);

            document.add(p);

            done++;
            progressBar.setValue(done);
        }

        // step 5: we close the document
        document.close();

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

}

From source file:net.refractions.udig.printing.ui.internal.PdfPrintingEngine.java

License:Open Source License

public boolean printToPdf() {

    Dimension paperSize = page.getPaperSize();
    Dimension pageSize = page.getSize();

    float xScale = (float) paperSize.width / (float) pageSize.width;
    float yScale = (float) paperSize.height / (float) pageSize.height;

    Rectangle paperRectangle = new Rectangle(paperSize.width, paperSize.height);
    Document document = new Document(paperRectangle, 0f, 0f, 0f, 0f);

    try {/*from  w ww .  j a  v a2 s.  c  om*/

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPdfFile));
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        Graphics2D graphics = cb.createGraphics(paperRectangle.getWidth(), paperRectangle.getHeight());

        // BufferedImage bI = new BufferedImage((int) paperRectangle.width(), (int)
        // paperRectangle
        // .height(), BufferedImage.TYPE_INT_ARGB);
        // Graphics graphics2 = bI.getGraphics();

        List<Box> boxes = page.getBoxes();
        for (Box box : boxes) {
            String id = box.getID();
            System.out.println(id);
            Point boxLocation = box.getLocation();
            if (boxLocation == null)
                continue;
            int x = boxLocation.x;
            int y = boxLocation.y;
            Dimension size = box.getSize();
            if (size == null)
                continue;
            int w = size.width;
            int h = size.height;

            float newX = xScale * (float) x;
            float newY = yScale * (float) y;
            float newW = xScale * (float) w;
            float newH = yScale * (float) h;

            box.setSize(new Dimension((int) newW, (int) newH));
            box.setLocation(new Point((int) newX, (int) newY));

            Graphics2D boxGraphics = (Graphics2D) graphics.create((int) newX, (int) newY, (int) newW,
                    (int) newH);
            BoxPrinter boxPrinter = box.getBoxPrinter();
            boxPrinter.draw(boxGraphics, monitor);
        }

        graphics.dispose();
        // ImageIO.write(bI, "png", new File("c:\\Users\\moovida\\Desktop\\test.png"));
        // graphics.drawImage(bI, null, 0, 0);

        document.newPage();
        document.close();
        writer.close();
    } catch (DocumentException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:net.sf.firemox.deckbuilder.BuildBook.java

License:Open Source License

/**
 * //w  w  w .  jav  a2  s  . c om
 */
@SuppressWarnings("unchecked")
public void build() {
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(MToolKit.getFile(checklist)),
                Charset.forName("ISO-8859-1")));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }
    // String charset = Charset.forName("ISO-8859-1").name();
    String line = null;
    int cur = 0;
    int row = 0;
    PdfPCell[] cells = new PdfPCell[3];
    PdfPTable table = new PdfPTable(3);
    Document document = new Document(PageSize.A4);
    try {
        PdfWriter.getInstance(document, new FileOutputStream(this.pdfBook));
        document.open();
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    try {
        in.readLine(); // Removing header line
        String[] tokens = new String[] { "\t", "\\s{2,}" };
        while ((line = in.readLine()) != null) {
            // line = new String(line.getBytes(),charset);
            // Card# Card Name Artist Color Rarity
            String[] fields = null;
            for (String token : tokens) {
                fields = line.split(token);
                if (fields.length == 5) {
                    break;
                }
            }

            if (fields == null || fields.length < 5) {
                System.err.println("Unable to parse " + line);
                continue;
            } else if (fields.length > 5) {
                System.out.println("Too many value found on " + line);
            }
            fields[1] = fields[1].trim();
            fields[1] = fields[1].replaceAll("[ -]", "_");
            fields[1] = fields[1].replaceAll("[/',\\u0092]", "");
            fields[1] = fields[1].replaceAll("", "AE");
            System.out.println("Inserting " + fields[1]);
            if (basicLands.containsKey(fields[1])) {
                int x = basicLands.get(fields[1]);
                cells[cur] = new PdfPCell(getImage(fields[1] + x), true);
                x++;
                basicLands.put(fields[1], x);
            } else {
                cells[cur] = new PdfPCell(getImage(fields[1]), true);
            }
            cur++;
            if (cur == 3) {
                for (int j = 0; j < cells.length; j++) {
                    cells[j].setPadding(2.0f);
                }
                table.getRows().add(new PdfPRow(cells));
                row++;
                cur = 0;
                cells = new PdfPCell[3];
            }
            if (row == 3) {
                table.setWidthPercentage(100);
                document.add(table);
                table = new PdfPTable(3);
                row = 0;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:net.sf.jasperreports.engine.export.JRPdfExporter.java

License:LGPL

/**
 *
 *//*from w  w w.jav  a 2s .c o m*/
protected void exportReportToStream(OutputStream os) throws JRException {
    //ByteArrayOutputStream baos = new ByteArrayOutputStream();

    document = new Document(new Rectangle(jasperPrint.getPageWidth(), jasperPrint.getPageHeight()));

    imageTesterDocument = new Document(new Rectangle(10, //jasperPrint.getPageWidth(),
            10 //jasperPrint.getPageHeight()
    ));

    boolean closeDocuments = true;
    try {
        pdfWriter = PdfWriter.getInstance(document, os);
        pdfWriter.setCloseStream(false);

        if (pdfVersion != null)
            pdfWriter.setPdfVersion(pdfVersion.charValue());

        if (isCompressed)
            pdfWriter.setFullCompression();

        if (isEncrypted) {
            pdfWriter.setEncryption(is128BitKey, userPassword, ownerPassword, permissions);
        }

        // Add meta-data parameters to generated PDF document
        // mtclough@users.sourceforge.net 2005-12-05
        String title = (String) parameters.get(JRPdfExporterParameter.METADATA_TITLE);
        if (title != null)
            document.addTitle(title);

        String author = (String) parameters.get(JRPdfExporterParameter.METADATA_AUTHOR);
        if (author != null)
            document.addAuthor(author);

        String subject = (String) parameters.get(JRPdfExporterParameter.METADATA_SUBJECT);
        if (subject != null)
            document.addSubject(subject);

        String keywords = (String) parameters.get(JRPdfExporterParameter.METADATA_KEYWORDS);
        if (keywords != null)
            document.addKeywords(keywords);

        String creator = (String) parameters.get(JRPdfExporterParameter.METADATA_CREATOR);
        if (creator != null)
            document.addCreator(creator);
        else
            document.addCreator("JasperReports (" + jasperPrint.getName() + ")");

        document.open();

        if (pdfJavaScript != null)
            pdfWriter.addJavaScript(pdfJavaScript);

        pdfContentByte = pdfWriter.getDirectContent();

        initBookmarks();

        PdfWriter imageTesterPdfWriter = PdfWriter.getInstance(imageTesterDocument, new NullOutputStream() // discard the output
        );
        imageTesterDocument.open();
        imageTesterDocument.newPage();
        imageTesterPdfContentByte = imageTesterPdfWriter.getDirectContent();
        imageTesterPdfContentByte.setLiteral("\n");

        for (reportIndex = 0; reportIndex < jasperPrintList.size(); reportIndex++) {
            jasperPrint = (JasperPrint) jasperPrintList.get(reportIndex);
            loadedImagesMap = new HashMap();
            document.setPageSize(new Rectangle(jasperPrint.getPageWidth(), jasperPrint.getPageHeight()));

            BorderOffset.setLegacy(JRProperties.getBooleanProperty(jasperPrint,
                    BorderOffset.PROPERTY_LEGACY_BORDER_OFFSET, false));

            List pages = jasperPrint.getPages();
            if (pages != null && pages.size() > 0) {
                if (isModeBatch) {
                    document.newPage();

                    if (isCreatingBatchModeBookmarks) {
                        //add a new level to our outline for this report
                        addBookmark(0, jasperPrint.getName(), 0, 0);
                    }

                    startPageIndex = 0;
                    endPageIndex = pages.size() - 1;
                }

                for (int pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) {
                    if (Thread.currentThread().isInterrupted()) {
                        throw new JRException("Current thread interrupted.");
                    }

                    JRPrintPage page = (JRPrintPage) pages.get(pageIndex);

                    document.newPage();

                    pdfContentByte = pdfWriter.getDirectContent();

                    pdfContentByte.setLineCap(2);//PdfContentByte.LINE_CAP_PROJECTING_SQUARE since iText 1.02b

                    writePageAnchor(pageIndex);

                    /*   */
                    exportPage(page);
                }
            } else {
                document.newPage();
                pdfContentByte = pdfWriter.getDirectContent();
                pdfContentByte.setLiteral("\n");
            }
        }

        closeDocuments = false;
        document.close();
        imageTesterDocument.close();
    } catch (DocumentException e) {
        throw new JRException("PDF Document error : " + jasperPrint.getName(), e);
    } catch (IOException e) {
        throw new JRException("Error generating PDF report : " + jasperPrint.getName(), e);
    } finally {
        if (closeDocuments) //only on exception
        {
            try {
                document.close();
            } catch (Throwable e) {
                // ignore, let the original exception propagate
            }

            try {
                imageTesterDocument.close();
            } catch (Throwable e) {
                // ignore, let the original exception propagate
            }
        }
    }

    //return os.toByteArray();
}

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

License:GNU General Public License

/**
 * Orders the pages from an DIN-A4-document on a DIN-A3-document.
 * @param reader reader for DIN-A4-document
 * @param pdfFileA3 file in which the A3-document will be saved.
 * @param pages page-numbers in the order they will placed the paper in the
 * order left, right-side must be a multiple of 4. 0 is interpreted as an
 * empty-page.//from  w w w  .jav a  2 s .c om
 * @throws DocumentException problems in iText.
 * @throws IOException io-problems.
 */
private void createA3Subdocument(PdfReader reader, File pdfFileA3, int... pages)
        throws DocumentException, IOException {
    if (pages.length % 4 != 0) {
        throw new IllegalArgumentException("The number of pages must be a " + "multiple of 4.");
    }

    // we retrieve the size of the first page
    final Rectangle psize = reader.getPageSize(1);
    final float width = psize.getWidth();
    final float leftMargin = 0f;
    final float topMargin = 0f;

    // step 1: creation of a document-object
    final Document document = new Document(PageSize.A3.rotate());
    // step 2: we create a writer that listens to the document
    final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFileA3));
    writer.setPDFXConformance(PdfWriter.PDFA1B);
    // step 3: we open the document
    document.open();
    addPdfAInfosToDictonary(writer);

    // step 4: we add content
    final PdfContentByte cb = writer.getDirectContent();
    final PdfTemplate[] pdfPages = new PdfTemplate[pages.length];
    for (int i = 0; i < pdfPages.length; i++) {
        final int pageNr = pages[i];
        final PdfTemplate page;
        if (pageNr == EMPTY_PAGE) {
            page = writer.getImportedPage(getEmptyPDFPage(psize), 1);
        } else {
            page = writer.getImportedPage(reader, pageNr);
        }

        if (i % 2 == 0) {
            document.newPage();
            cb.addTemplate(page, 1f, 0f, 0f, 1f, leftMargin, topMargin);
        } else {
            cb.addTemplate(page, 1f, 0f, 0f, 1f, width + leftMargin, topMargin);
        }

    }

    writer.createXmpMetadata();
    // step 5: we close the document
    document.close();
}

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

License:GNU General Public License

/**
 * Creates an document with an emptyPage.
 * @param pageSize the size of the Page.
 * @return a reader with 1 empty-page.//w w w .  j a v a 2 s. co  m
 */
private synchronized PdfReader getEmptyPDFPage(Rectangle pageSize) {
    if (emptyPdfPage == null) {
        try {
            final int initialByteSize = 1024;
            final ByteArrayOutputStream baos = new ByteArrayOutputStream(initialByteSize);
            final Document emptyDoc = new Document(pageSize);
            final PdfWriter w = PdfWriter.getInstance(emptyDoc, baos);
            emptyDoc.open();
            w.getDirectContent().setLiteral(' ');
            emptyDoc.close();
            this.emptyPdfPage = new PdfReader(baos.toByteArray());
        } catch (Exception e) {
            LOG.error("Can't create an empty-page", e);
        }
    }

    return emptyPdfPage;
}