Example usage for com.lowagie.text Document open

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

Introduction

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

Prototype

boolean open

To view the source code for com.lowagie.text Document open.

Click Source Link

Document

Is the document open or not?

Usage

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

License:Open Source License

/**
 * Convert HTML to PDF/*from   w  ww.j  ava 2  s  . c  o m*/
 */
public void html2pdf(File input, File output) throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from HTML to PDF **");
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(output);

        // Make conversion
        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, fos);
        doc.open();
        HTMLWorker html = new HTMLWorker(doc);
        html.parse(new FileReader(input));
        doc.close();
    } 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

/**
 * Convert TXT to PDF/*from   www . j  a  v  a 2 s  .  c  o  m*/
 */
public void txt2pdf(InputStream is, File output) throws ConversionException, DatabaseException, IOException {
    log.debug("** Convert from TXT to PDF **");
    FileOutputStream fos = null;
    String line = null;

    try {
        fos = new FileOutputStream(output);

        // Make conversion
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        Document doc = new Document(PageSize.A4);
        PdfWriter.getInstance(doc, fos);
        doc.open();

        while ((line = br.readLine()) != null) {
            doc.add(new Paragraph(12F, line));
        }

        doc.close();
    } 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

/**
 * Convert ZIP to PDF/*from  ww w. j a v  a 2s  .  c o  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//from  ww w.j  a  v a 2s  . 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);//from  w  w  w  .jav  a  2  s.c om
    doc.open();

    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/*ww w  . ja v  a  2s .  c om*/

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/*  w ww  . ja v a2  s.c  om*/
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  om
 *
 * @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.pdf.PDFMergeUtil.java

License:Apache License

/**
 * Concat PD fs./* w  ww . ja v  a 2s.  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.DocumentManager.java

/**
 *
 * @param document//ww  w .  j av a  2 s  . c o m
 */
public void preProcessPDF(Object document) {
    try {

        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);

        Document pdf = (Document) document;
        pdf.setPageSize(PageSize.A4);
        pdf.setMargins(5f, 5f, 10f, 5f);

        // headers and footers must be added before the document is opened
        HeaderFooter footer = new HeaderFooter(new Phrase("page: ", new Font(bf_courier)), true);
        footer.setBorder(Rectangle.NO_BORDER);
        footer.setAlignment(Element.ALIGN_CENTER);
        pdf.setFooter(footer);

        //            HeaderFooter header = new HeaderFooter(
        //                        new Phrase("This is a header without a page number", new Font(bf_courier)), false);
        //            header.setAlignment(Element.ALIGN_CENTER);
        //            pdf.setHeader(header);

        pdf.open();

        String logoPath = "/resources/image/logo.png";
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String logo = servletContext.getRealPath(logoPath);

        pdf.add(Image.getInstance(logo));

        Person person = context.getSelectedPerson().getDisplayPerson();

        String name = FacesMessageUtil.getMessage("person.name") + " : " + person.getName();
        String age = FacesMessageUtil.getMessage("person.age") + " : " + Integer.toString(person.getAge());
        String gender = FacesMessageUtil.getMessage("person.gender") + " : "
                + person.getGender().getDescription();
        String race = FacesMessageUtil.getMessage("person.ethnicity") + " : "
                + person.getEthnicity().getDescription();

        Person rootPerson = person.getRootPerson();
        PersonImage imgp = imageService.getLastestPersonImage(rootPerson.getId());
        Image imgb = Image.getInstance(imgp.getContent());
        imgb.scaleToFit(100, 120);

        PdfPTable headerTable = new PdfPTable(2);

        PdfPTable personTable = new PdfPTable(1);
        personTable.setWidthPercentage(100);
        PdfPCell cell;

        cell = new PdfPCell(new Phrase(name));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(age));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(gender));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        cell = new PdfPCell(new Phrase(race));
        cell.setBorder(Rectangle.NO_BORDER);
        personTable.addCell(cell);

        BarcodePDF417 pdf417 = new BarcodePDF417();
        pdf417.setText(Integer.toString(person.getId()));
        Image img = pdf417.getImage();
        img.scalePercent(150, 60 * pdf417.getYHeight());
        cell = new PdfPCell(img);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setPaddingTop(15);
        personTable.addCell(cell);

        cell.addElement(personTable);
        headerTable.addCell(cell);

        cell = new PdfPCell(imgb);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(Rectangle.NO_BORDER);
        headerTable.addCell(cell);

        headerTable.setSpacingAfter(15);
        pdf.add(headerTable);

        LineSeparator lineSeparator = new LineSeparator();
        lineSeparator.setPercentage(82);
        pdf.add(lineSeparator);
        Paragraph space = new Paragraph();
        space.add("");
        space.setSpacingAfter(15);
        pdf.add(space);

    } catch (IOException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (BadElementException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (DocumentException e) {
        logger.log(Level.INFO, e.getMessage());
    } catch (Exception e) {
        logger.log(Level.INFO, e.getMessage());
    }

}