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:cz.incad.kramerius.rest.api.k5.client.pdf.PDFResource.java

License:Open Source License

private static StreamingOutput streamingOutput(final File file, final String format) {
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                Rectangle formatRect = formatRect(format);
                Document document = new Document(formatRect);
                PdfWriter.getInstance(document, output);
                document.open();/*  ww w. j  av  a2s . c om*/

                Image image = Image.getInstance(file.toURI().toURL());

                image.scaleToFit(
                        document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(),
                        document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin());
                document.add(image);

                document.close();

            } catch (Exception e) {
                throw new WebApplicationException(e);
            } finally {
                if (file != null)
                    file.delete();
            }
        }
    };
}

From source file:datasoul.servicelist.ServiceListExporterDocument.java

License:Open Source License

public ServiceListExporterDocument(int type, String filename, boolean exportGuitarTabs)
        throws FileNotFoundException, DocumentException {
    document = new Document();

    // ensure file do not exist to avoid garbage at the end of the file
    File f = new File(filename);
    if (f.exists()) {
        f.delete();//from  w w w.j av  a 2  s. c  o m
    }

    if (type == TYPE_RTF) {
        RtfWriter2.getInstance(document, new FileOutputStream(filename));
    } else {
        PdfWriter w = PdfWriter.getInstance(document, new FileOutputStream(filename));
        w.setStrictImageSequence(true);
    }
    document.open();
    document.addCreator("Datasoul " + DatasoulMainForm.getVersion());
    document.addCreationDate();

    this.exportGuitarTabs = exportGuitarTabs;
    if (exportGuitarTabs) {
        guitarTabs = new LinkedList<Paragraph>();
    }
}

From source file:datasoul.servicelist.ServiceListExporterSlides.java

License:Open Source License

public ServiceListExporterSlides(String filename, int width, int height)
        throws FileNotFoundException, DocumentException {
    document = new Document();
    deleteOnDispose = new LinkedList<String>();
    slideCount = 0;//from  w  ww .  ja  va 2  s.  c  om

    // ensure file do not exist to avoid garbage at the end of the file
    File f = new File(filename);
    if (f.exists()) {
        f.delete();
    }
    PdfWriter.getInstance(document, new FileOutputStream(filename));

    document.setMargins(0, 0, 0, 0);

    document.setPageSize(new Rectangle(width, height));
    document.open();
    document.addCreator("Datasoul " + DatasoulMainForm.getVersion());
    document.addCreationDate();

    render = new ExporterContentRender(width, height, new DummyContentDisplay());

}

From source file:de.appplant.cordova.plugin.printer.Printer.java

License:Apache License

/**
 * Slices the screenshot into pages, merges those into a single pdf
 * and saves it in the public accessible /sdcard dir.
 *///  w  ww  .j  a  v  a2  s .  c  o m
private File saveWebViewAsPdf(Bitmap screenshot) {
    try {

        File sdCard = Environment.getExternalStorageDirectory();
        File dir = new File(sdCard.getAbsolutePath() + "/" + this.publicTmpDir + "/");
        dir.mkdirs();
        File file;
        FileOutputStream stream;

        double pageWidth = PageSize.A4.getWidth() * 0.85; // width of the image is 85% of the page
        double pageHeight = PageSize.A4.getHeight() * 0.80; // max height of the image is 80% of the page
        double pageHeightToWithRelation = pageHeight / pageWidth; // e.g.: 1.33 (4/3)

        Bitmap currPage;
        int totalSize = screenshot.getHeight();
        int currPos = 0;
        int currPageCount = 0;
        int sliceWidth = screenshot.getWidth();
        int sliceHeight = (int) Math.round(sliceWidth * pageHeightToWithRelation);
        while (totalSize > currPos && currPageCount < 100) // max 100 pages
        {
            currPageCount++;

            Log.v(LOG_TAG, "Creating page nr. " + currPageCount);

            // slice bitmap
            currPage = Bitmap.createBitmap(screenshot, 0, currPos, sliceWidth,
                    (int) Math.min(sliceHeight, totalSize - currPos));

            // save page as png
            stream = new FileOutputStream(new File(dir, "print-page-" + currPageCount + ".png"));
            currPage.compress(Bitmap.CompressFormat.PNG, 100, stream);
            stream.close();

            // move current position indicator
            currPos += sliceHeight;
        }

        // create pdf
        Log.v(LOG_TAG, "Creating pdf");
        Document document = new Document();
        File filePdf = new File(dir, this.printTitle + ".pdf"); // change the output name of the pdf here
        PdfWriter.getInstance(document, new FileOutputStream(filePdf));
        document.open();
        for (int i = 1; i <= currPageCount; ++i) {
            Log.v(LOG_TAG, "Adding page nr. " + i + " to the pdf file.");
            file = new File(dir, "print-page-" + i + ".png");
            Image image = Image.getInstance(file.getAbsolutePath());
            image.scaleToFit((float) pageWidth, 9999);
            image.setAlignment(Element.ALIGN_CENTER);
            document.add(image);
            document.newPage();
        }
        document.close();

        // delete tmp image files
        for (int i = 1; i <= currPageCount; ++i) {
            file = new File(dir, "print-page-" + i + ".png");
            file.delete();
        }

        return filePdf;

    } catch (IOException e) {
        Log.e(LOG_TAG, "ERROR: " + e.getMessage());
        e.printStackTrace();
        // return error answer to cordova
        PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        result.setKeepCallback(false);
        ctx.sendPluginResult(result);
    } catch (DocumentException e) {
        Log.e(LOG_TAG, "ERROR: " + e.getMessage());
        e.printStackTrace();
        // return error answer to cordova
        PluginResult result = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        result.setKeepCallback(false);
        ctx.sendPluginResult(result);
    }

    Log.e(LOG_TAG, "Uncaught ERROR!");

    return null;
}

From source file:de.atomfrede.tools.evalutation.tools.plot.util.PlotUtil.java

License:Open Source License

protected static void writeChartAsPDF(OutputStream out, JFreeChart chart, int width, int height,
        FontMapper mapper) throws IOException {
    Rectangle pagesize = new Rectangle(width, height);
    Document document = new Document(pagesize, 50, 50, 50, 50);
    try {//from w w  w  .j av a  2s. c om
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2 = tp.createGraphics(width, height, mapper);
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2, r2D);
        g2.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    }
    document.close();
}

From source file:de.chott.jfreechartsample.service.ChartService.java

/**
 * Schreibt mehrere JFreeCharts in ein PDF. Fr jedes Chart wird hierbei eine halbe PDF-Seite verwendet.
 * //from w  ww . j  av a2s  . com
 * @param charts
 * @return Das PDF als ByteArray
 */
private byte[] writeChartsToDocument(JFreeChart... charts) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight() / 2;
        int index = 0;

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        document.open();
        PdfContentByte contentByte = writer.getDirectContent();

        for (JFreeChart chart : charts) {

            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphics2D = template.createGraphics(width, height);
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);

            chart.draw(graphics2D, rectangle2D);

            graphics2D.dispose();
            contentByte.addTemplate(template, 0, height - (height * index));
            index++;
        }

        writer.flush();
        document.close();

        return baos.toByteArray();
    } catch (Exception ex) {
        Logger.getLogger(ChartService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:de.cuseb.bilderbuch.pdf.PdfController.java

License:Open Source License

@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) {

    try {/*from ww  w.  j a  va2 s.  c  o  m*/
        PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest");
        httpServletResponse.setContentType("application/pdf");

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream());
        writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB);

        //document.addAuthor(pdfRequest.getAuthor());
        //document.addTitle(pdfRequest.getTitle());
        document.setPageSize(
                new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148)));
        document.open();

        FontFactory.defaultEmbedding = true;
        FontFactory.register("IndieRock.ttf", "IndieRock");
        Font font = FontFactory.getFont("IndieRock");
        BaseFont baseFont = font.getBaseFont();
        PdfContentByte cb = writer.getDirectContent();

        Iterator<PdfPage> pages = pdfRequest.getPages().iterator();
        while (pages.hasNext()) {

            PdfPage page = pages.next();
            if (page.getImage() != null) {

                Image image = Image.getInstance(new URL(page.getImage().getUrl()));
                image.setDpi(300, 300);
                image.setAbsolutePosition(0f, 0f);
                image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight());
                document.add(image);

                cb.saveState();
                cb.beginText();
                cb.setColorFill(Color.WHITE);
                cb.moveText(10f, 10f);
                cb.setFontAndSize(baseFont, 18);
                cb.showText(page.getSentence());
                cb.endText();
                cb.restoreState();

                if (pages.hasNext()) {
                    document.newPage();
                }
            }
        }
        document.close();

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

From source file:de.d3web.empiricaltesting.casevisualization.jung.JUNGCaseVisualizer.java

License:Open Source License

/**
 * Streams the graph to an OutputStream (useful for web requests!)
 * //from  w  w  w . j  a v  a 2  s. c  o m
 * @param cases List<SequentialTestCase> cases
 * @param outStream OutputStream
 */
@Override
public void writeToStream(java.util.List<SequentialTestCase> cases, java.io.OutputStream outStream)
        throws IOException {

    init(cases);

    int w = vv.getGraphLayout().getSize().width;
    int h = vv.getGraphLayout().getSize().height;

    Document document = new Document();

    try {

        PdfWriter writer = PdfWriter.getInstance(document, outStream);
        document.setPageSize(new Rectangle(w, h));
        document.open();

        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(w, h);
        Graphics2D g2 = tp.createGraphics(w, h);
        paintGraph(g2);

        g2.dispose();
        tp.sanityCheck();
        cb.addTemplate(tp, 0, 0);
        cb.sanityCheck();

        document.close();

    } catch (DocumentException e) {
        throw new IOException("Error while writing to file. The file was not created. ", e);
    }
}

From source file:de.dfki.owlsmx.gui.util.Converter.java

License:Open Source License

public static void convertToPdf(JFreeChart chart, int width, int height, String filename) {
    // step 1       
    Document document = new Document(new Rectangle(width, height));
    try {/*from  w ww.  j  av  a2 s  .co  m*/
        // step 2
        PdfWriter writer;
        writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        cb.addTemplate(tp, 0, 0);
    } catch (DocumentException de) {

    } catch (FileNotFoundException e) {

    }
    // step 5
    document.close();
}

From source file:de.dhbw.humbuch.util.PDFHandler.java

/**
 * Creates the pdf with the information in the object that was passed to the
 * constructor previously.//from  w ww.ja  va  2 s  .  c  om
 * 
 * @param path
 *            where the file will be saved
 */
public void savePDF(String path) {
    try {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path));
        event = new HeaderFooter();
        writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
        writer.setPageEvent(event);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    this.document.open();
    this.addMetaData(document);
    this.insertDocumentParts(document);
    this.document.close();
}