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:com.ikon.util.DocConverter.java

License:Open Source License

/**
 * Convert ZIP to PDF/*from  ww w. jav  a 2 s.co  m*/
 */
@SuppressWarnings("rawtypes")
public void zip2pdf(File input, File output) throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from ZIP to PDF **");
    FileOutputStream fos = null;
    ZipFile zipFile = null;

    try {
        fos = new FileOutputStream(output);

        // Make conversion
        zipFile = new ZipFile(input);
        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, fos);
        doc.open();

        for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            doc.add(new Paragraph(12F, entry.getName()));
        }

        doc.close();
        zipFile.close();
    } catch (ZipException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Exception in conversion: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.ikon.util.DocConverter.java

License:Open Source License

/**
 * TIFF to PDF conversion//  ww w.j a v a2  s . c  o  m
 */
public void tiff2pdf(File input, File output) throws ConversionException {
    RandomAccessFileOrArray ra = null;
    Document doc = null;

    try {
        // Open PDF
        doc = new Document();
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
        PdfContentByte cb = writer.getDirectContent();
        doc.open();
        //int pages = 0;

        // Open TIFF
        ra = new RandomAccessFileOrArray(input.getPath());
        int comps = TiffImage.getNumberOfPages(ra);

        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);

            if (img != null) {
                log.debug("tiff2pdf - page {}", c + 1);

                if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                    img.scaleToFit(500, 700);
                }

                img.setAbsolutePosition(20, 20);
                //doc.add(new Paragraph("page " + (c + 1)));
                cb.addImage(img);
                doc.newPage();
                //++pages;
            }
        }
    } catch (FileNotFoundException e) {
        throw new ConversionException("File not found: " + e.getMessage(), e);
    } catch (DocumentException e) {
        throw new ConversionException("Document exception: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new ConversionException("IO exception: " + e.getMessage(), e);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        if (doc != null) {
            doc.close();
        }
    }
}

From source file:com.ikon.util.PDFUtils.java

License:Open Source License

public static void generateSample(int paragraphs, OutputStream os) throws DocumentException {
    LoremIpsum li = new LoremIpsum();
    Document doc = new Document(PageSize.A4, 25.0F, 25.0F, 25.0F, 25.0F);
    PdfWriter.getInstance(doc, os);
    doc.open();//from w ww . j av a 2  s. co m

    for (int i = 0; i < paragraphs; i++) {
        doc.add(new Paragraph(li.getParagraphs()));
    }

    doc.close();
}

From source file:com.isdemu.controller.DepreciacionController.java

@RequestMapping(value = "/ExcelReporteInvPersona2", method = RequestMethod.GET)
@ResponseBody//from w  ww .  j a v  a  2 s. c  o m

public void getRptAsig2(HttpServletResponse response)
        throws JRException, IOException, SQLException, ClassNotFoundException {
    Document document = new Document();
    try {
        response.setContentType("application/pdf");
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        document.add(new Paragraph("howtodoinjava.com"));
        document.add(new Paragraph(new Date().toString()));
        //Add more content here
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("response :" + response);
    document.close();
}

From source file:com.isdemu.controller.TBS_UsuarioController.java

@RequestMapping(value = "/codigo_barra", method = RequestMethod.POST)
@ResponseBody//  ww w  .jav a2 s. co  m
public String codigo(@RequestBody String codigos) throws FileNotFoundException, DocumentException {

    JSONObject array = new JSONObject(codigos);

    Document document = new Document();

    File file = new File(this.getClass().getResource("/codigoBarraIsdemu.pdf").getFile());

    String absolutePath = file.getAbsolutePath();

    absolutePath = absolutePath.replaceAll("%20", " ");

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

    Rectangle one = new Rectangle(76, 35);
    document.setPageSize(one);
    document.setMargins(2, 2, 2, 2);

    document.open();

    Barcode128 code128 = new Barcode128();
    code128.setGenerateChecksum(true);

    JSONArray object = array.getJSONArray("Inventario");
    for (int i = 0; i < object.length(); i++) {
        JSONObject object2 = object.getJSONObject(i);

        //JSONArray object = array.getJSONArray("Inventario");
        String id = object2.getString("idInv");

        code128.setCode(id);
        document.add(code128.createImageWithBarcode(writer.getDirectContent(), null, null));

        document.newPage();

    }

    document.close();

    return "Almacenado";

}

From source file:com.iver.cit.gvsig.project.documents.layout.FLayoutDraw.java

License:Open Source License

/**
 * A partir de un fichero que se pasa como parmetro se crea un pdf con el
 * contenido del Layout./*from  w  ww .  j  a v a  2s . c o m*/
 *
 * @param pdf
 */
public void toPDF(File pdf) {
    Attributes attributes = layout.getLayoutContext().getAttributes();
    LayoutControl layoutControl = layout.getLayoutControl();

    double w = 0;
    double h = 0;
    Document document = new Document();

    if (attributes.isLandSpace()) {
        w = ((attributes.m_sizePaper.getAlto() * Attributes.DPISCREEN) / Attributes.PULGADA);
        h = ((attributes.m_sizePaper.getAncho() * Attributes.DPISCREEN) / Attributes.PULGADA);
    } else {
        w = ((attributes.m_sizePaper.getAncho() * Attributes.DPISCREEN) / Attributes.PULGADA);
        h = ((attributes.m_sizePaper.getAlto() * Attributes.DPISCREEN) / Attributes.PULGADA);
    }

    document.setPageSize(new com.lowagie.text.Rectangle((float) w, (float) h));

    try {
        FileOutputStream fos = new FileOutputStream(pdf);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        document.open();

        Print print = new Print();
        print.setLayout(layout);

        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g2 = cb.createGraphicsShapes((float) w, (float) h);

        try {
            if (attributes.isLandSpace()) {
                g2.rotate(Math.toRadians(-90), 0 + (w / (h / w)), 0 + (h / 2));
                print.print(g2, new PageFormat(), 0);
                g2.rotate(Math.toRadians(90), 0 + (w / (h / w)), 0 + (h / 2));
            } else {
                print.print(g2, new PageFormat(), 0);
            }
        } catch (PrinterException e) {
            e.printStackTrace();
        }

        g2.dispose();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog((Component) PluginServices.getMainFrame(), ioe.getMessage());
    }

    document.close();

    layoutControl.fullRect();
}

From source file:com.jk.framework.desktop.swing.dao.TableModelPdfBuilder.java

License:Apache License

/**
 * Builds the pdf document.//from  w  ww.  j a  v  a 2  s .  c o m
 *
 * @param out
 *            the out
 * @throws ReportException
 *             the report exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void buildPdfDocument(final OutputStream out) throws ReportException, IOException {
    this.document = new Document(getPageRotation());
    try {
        this.writer = PdfWriter.getInstance(this.document, out);
        this.document.open();
        final PdfPTable pdfPTable = createPdfTable();

        this.document.add(pdfPTable);
        this.document.close();
    } catch (final DocumentException e) {
        throw new ReportException(e);
    }
}

From source file:com.jk.framework.pdf.JKPDFDocument.java

License:Apache License

/**
 * Open document./*w  ww .j  a v a 2  s  .c  o  m*/
 *
 * @throws DocumentException
 *             the document exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void openDocument() throws DocumentException, IOException {
    this.writer = PdfWriter.getInstance(this, this.out);

    if (this.headerText != null) {
        final HeaderFooter header = new HeaderFooter(new Phrase(this.headerText), false);
        setHeader(header);
    }
    if (this.footerText != null) {
        final HeaderFooter footer = new HeaderFooter(new Phrase(this.footerText), false);
        setFooter(footer);
    }
    super.open();
}

From source file:com.jk.framework.pdf.PDFMergeUtil.java

License:Apache License

/**
 * Concat PD fs.//from  w ww  .jav a2  s . c o  m
 *
 * @param pdfs
 *            the pdfs
 * @param outputStream
 *            the output stream
 * @param paginate
 *            the paginate
 * @throws PdfException
 *             the pdf exception
 */
// ////////////////////////////////////////////////////////////////
public static void concatPDFs(final List<InputStream> pdfs, final OutputStream outputStream,
        final boolean paginate) throws PdfException {
    final Document document = new Document();
    try {
        final List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        final Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            final InputStream pdf = iteratorPDFs.next();
            final PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }

        // Create a writer for the outputstream
        final PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();

        // BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
        // BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        final PdfContentByte cb = writer.getDirectContent(); // Holds the
        // PDF
        // data

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        final Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            final PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    // cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                            "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }

        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (final Exception e) {
        throw new PdfException(e);
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (final IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:com.kahlon.guard.controller.example.SimpleBean.java

public void createPDF() {
    try { //catch better your exceptions, this is just an example
        FacesContext context = FacesContext.getCurrentInstance();
        Document document = new Document();
        String fileName = "PDFFile";
        String TEXT = FacesMessageUtil.getMessage("person.name") + "  --  "
                + "These are the protagonists in 'Hero', a movie by Zhang Yimou:\n"
                + "\u7121\u540d (Nameless), \u6b98\u528d (Broken Sword), "
                + "\u98db\u96ea (Flying Snow), \u5982\u6708 (Moon), "
                + "\u79e6\u738b (the King), and \u9577\u7a7a (Sky).";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);

        if (!document.isOpen()) {
            document.open();/*  w  w  w  .  j a va2s  .  c om*/
        }

        writer.getAcroForm().setNeedAppearances(true);

        TextField text = new TextField(writer, new Rectangle(36, 806, 559, 780), "description");
        text.setOptions(TextField.MULTILINE);
        //text.setOptions(TextField.READ_ONLY);
        text.setText(TEXT);

        writer.addAnnotation(text.getTextField());

        //document.add(new Phrase(TEXT));

        //Keep modifying your pdf file (add pages and more)
        document.close();

        writePDFToResponse(context.getExternalContext(), baos, fileName);

        context.responseComplete();

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