Example usage for com.itextpdf.text Document Document

List of usage examples for com.itextpdf.text Document Document

Introduction

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

Prototype


public Document() 

Source Link

Document

Constructs a new Document -object.

Usage

From source file:com.gadroves.gsisinve.controller.FacturarController.java

void PrintToPDF(TbFacturaVenta facturaVenta, TbCLienteFactura cLienteFactura)
        throws DocumentException, IOException {
    Font header = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
    Font normalBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
    Font normal = new Font(Font.FontFamily.HELVETICA, 12);
    String fileName = "Factura_" + facturaVenta.getId() + ".pdf";
    // step 1// ww w.  j  av a  2  s .c  om
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(fileName));
    // step 3
    document.open();
    // step 4
    document.add(new Paragraph("Gadroves S.A Factura De Venta", header));
    document.add(new Paragraph(" "));
    document.add(new Paragraph("Factura N" + facturaVenta.getId(), normalBold));
    document.add(new Chunk("Cliente:            ", normalBold));
    document.add(new Chunk(" "));
    document.add(new Chunk(cLienteFactura.getName(), normal));

    document.add(new Paragraph());
    document.add(new Chunk("Direccin:        ", normalBold));
    document.add(new Chunk(" "));
    document.add(new Chunk(cLienteFactura.getAddress(), normal));

    document.add(new Paragraph());
    document.add(new Chunk("Identificacion: ", normalBold));
    document.add(new Chunk(" "));
    document.add(new Chunk(cLienteFactura.getId(), normal));

    document.add(new Paragraph());
    document.add(new Chunk("Credito:            ", normalBold));
    document.add(new Chunk(" "));
    document.add(new Chunk(Boolean.FALSE.toString(), normal));
    document.add(new Paragraph());

    for (int i = 0; i < 3; i++)
        document.add(new Paragraph(" "));
    createItemsTable(document, facturaVenta);
    document.add(new Paragraph(" "));
    Paragraph subs = new Paragraph();

    subs.setAlignment(Element.ALIGN_RIGHT);
    subs.setIndentationRight(40);
    subs.add(new Chunk("Subtotal:  " + String.format("%1$" + 10 + "s", String.valueOf(facturaVenta.getSub()))));
    subs.add(Chunk.NEWLINE);
    subs.add(new Chunk(
            "Impuestos:  " + String.format("%1$" + 10 + "s", String.valueOf(facturaVenta.getImpuestos()))));
    subs.add(Chunk.NEWLINE);
    subs.add(new Chunk(
            "Total:       " + String.format("%1$" + 10 + "s", String.valueOf(facturaVenta.getTotal()))));
    subs.add(Chunk.NEWLINE);
    document.add(subs);
    // step 5

    document.close();
    Desktop.getDesktop().open(new File(fileName));
}

From source file:com.github.albfernandez.joinpdf.JoinPdf.java

License:Open Source License

public final synchronized void export(final OutputStream os) throws Exception {
    checkParameters();/*from  w  ww  .  j  ava  2  s  .c o  m*/
    Document document = new Document();

    try {
        if (isPrintPageNumbers()) {
            this.totalPages = gePageCount();
            this.actualPage = 0;
        }
        PdfWriter writer = PdfWriter.getInstance(document, os);
        setParametersAndHeaders(writer, document);
        document.open();
        for (File file : this.files) {
            add(file, document, writer);
        }
    } finally {
        ItextUtils.close(document);
    }
}

From source file:com.github.hossman.PdfShrinker.java

License:Apache License

public static void main(String args[]) throws Exception {
    if (1 != args.length) {
        System.err.println("Run this app with a single command line PDF filename");
        System.err.println("The specified file will be read, and a shrunk version written to stdout");
        System.err.println("ie:   java -jar pdf-shrinker.jar big.pdf > small.pdf");
        System.exit(-1);/*from   ww  w  . j  ava  2s  . c  o  m*/
    }

    Document document = new Document();
    PdfSmartCopy copy = new PdfSmartCopy(document, System.out);
    copy.setCompressionLevel(9);
    copy.setFullCompression();
    document.open();
    PdfReader reader = new PdfReader(args[0]);
    List<HashMap<String, Object>> bookmarks = SimpleBookmark.getBookmark(reader);
    int pages = reader.getNumberOfPages();
    for (int i = 0; i < pages; i++) {
        PdfImportedPage page = copy.getImportedPage(reader, i + 1);
        copy.addPage(page);
    }
    copy.freeReader(reader);
    reader.close();
    copy.setOutlines(bookmarks);
    document.close();
}

From source file:com.github.luischavez.levsym.modulos.funcion.PDF.java

License:Open Source License

public void CreateTablePDF(JTable tabla) {
    boolean shapes = false;
    Document document = new Document();
    Calendar c = Calendar.getInstance();
    String date = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "-" + Integer.toString(c.get(Calendar.MONTH))
            + "-" + Integer.toString(c.get(Calendar.YEAR)) + " " + Integer.toString(c.get(Calendar.HOUR_OF_DAY))
            + "-" + Integer.toString(c.get(Calendar.MINUTE)) + "-" + Integer.toString(c.get(Calendar.SECOND));
    File Dir = new File(System.getProperty("user.dir") + "/Reportes/");
    if (!Dir.exists()) {
        Dir.mkdirs();//from  w w w  .  j  av a 2  s. c  om
    }
    try {
        PdfWriter writer;
        if (shapes) {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        } else {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(System.getProperty("user.dir") + "/Reportes/Tabla " + date + ".pdf"));
        }

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(500, 500);
        Graphics2D g2;
        if (shapes) {
            g2 = tp.createGraphicsShapes(500, 500);
        } else {
            g2 = tp.createGraphics(500, 500);
        }

        g2.dispose();
        cb.addTemplate(tp, 30, 300);
    } catch (Exception e) {
        Log.SaveLog(e.toString());
    }
    document.close();
}

From source file:com.github.ossdevs.jhocr.converter.HocrToPdf.java

License:Open Source License

/**
 * This is the old <code>convert()</code> method, almost untouched.<br>
 * This method will be used if {@link #pdfFormat} is not set.
 *
 * @return true if the conversion was successful.
 *///from   w w w.  j ava 2 s  .  c  o  m
private boolean convertSimple() {
    boolean result = false;

    Document document = new Document();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, getOutputStream());

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;
}

From source file:com.github.ossdevs.jhocr.converter.HocrToPdf.java

License:Open Source License

/**
 * @param pdfXConformance determines into which format the PDF-X will be converted.
 * @return true if the conversion was successful.
 *///  w ww. j a  v a 2  s  .c o  m
private boolean convertToPDFX(int pdfXConformance) {
    boolean result = false;
    Document document = new Document();

    try {
        PdfWriter writer = PdfWriter.getInstance(document, getOutputStream());
        writer.setPDFXConformance(pdfXConformance);

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;

}

From source file:com.github.ossdevs.jhocr.converter.HocrToPdf.java

License:Open Source License

/**
 * @param pdfConformanceLevel determines into which format the PDF-A&/B will be converted.
 * @return true if the conversion was successful.
 *//* ww w. j a  va 2  s  . c  o m*/
private boolean convertToPDFA(PdfAConformanceLevel pdfConformanceLevel) {
    boolean result = false;
    Document document = new Document();

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    if (classLoader == null) {
        classLoader = Class.class.getClassLoader();
    }

    try {
        PdfAWriter writer = PdfAWriter.getInstance(document, getOutputStream(), pdfConformanceLevel);
        writer.createXmpMetadata();

        document.open();
        document.addHeader(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE);
        document.setMargins(0, 0, 0, 0);

        /**
         * TODO add documentation
         */
        for (HocrDocumentItem item : getItems()) {

            HocrParser parser = new HocrParser(item.getHocrInputStream());

            HocrDocument hocrDocument = parser.parse();

            /**
             * TODO add documentation
             * TODO add multipage image support
             */
            if (hocrDocument.getPages().size() > 1) {
                throw new UnsupportedOperationException(
                        "Multipage tif are not yet implemented, please report: http://code.google.com/p/jhocr/issues/list");
            }

            /**
             * TODO add documentation
             */
            for (HocrPage hocrPage : hocrDocument.getPages()) {
                HocrPageProcessor pageProcessor = new HocrPageProcessor(hocrPage, item.getImageInputStream(),
                        isUseImageDpi());

                if (pageProcessor.isInitialized()) {
                    pageProcessor.process(document, writer);
                }
            }
        }

        if (!outlines.isEmpty()) {
            writer.setOutlines(outlines);
        }

        InputStream is = this.getClass().getResourceAsStream("/sRGB.profile");

        ICC_Profile icc = ICC_Profile.getInstance(is);
        writer.setOutputIntents(KEY_JHOCR_INFO, KEY_JHOCR_INFO_VALUE, "http://www.color.org",
                "sRGB IEC61966-2.1", icc);

        /**
         * Closing the document body stream.
         */
        document.close();
        getOutputStream().close();
        result = true;

    } catch (UnsupportedOperationException e) {
        document.close();
        logger.error("This operation is not yet implemented.", e);
        result = false;
    } catch (DocumentException e) {
        document.close();
        logger.error("exception while genrating the PDF.", e);
        result = false;
    } catch (IOException e) {
        document.close();
        logger.error("FileSystem I/O Exception, please check the log and file system persmissions.", e);
        result = false;
    }

    return result;

}

From source file:com.github.sgelb.sldownloader.model.Pdf.java

License:Open Source License

public void mergePdfs() throws DocumentException, IOException {
    String title = book.getPdfTitle() + ".pdf";
    File saveFile = new File(saveFolder, title);

    int count = 1;
    while (saveFile.exists()) {
        title = book.getPdfTitle() + "_" + count++ + ".pdf";
        saveFile = new File(saveFolder, title);
    }//from w  w  w.j av a 2  s.co m
    book.setInfo("saveFile", saveFile.toString());

    Document document = new Document();
    PdfCopy destPdf = new PdfCopy(document, new FileOutputStream(saveFile));
    document.open();
    PdfReader reader;
    int page_offset = 0;
    int n;
    ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<HashMap<String, Object>>();
    List<HashMap<String, Object>> tmp;

    count = 1;
    System.out.println("Start mergin\u2026");
    for (File srcPdf : src) {

        if (Thread.interrupted()) {
            return;
        }

        System.out.print(":: " + count++ + "/" + src.size());
        reader = new PdfReader(srcPdf.toString());

        tmp = SimpleBookmark.getBookmark(reader);
        if (tmp != null) {
            SimpleBookmark.shiftPageNumbers(tmp, page_offset, null);
            bookmarks.addAll(tmp);
        }

        n = reader.getNumberOfPages();
        page_offset += n;
        for (int page = 0; page < n;) {
            destPdf.addPage(destPdf.getImportedPage(reader, ++page));
        }
        destPdf.freeReader(reader);
        reader.close();
        System.out.println(" succeed.");
    }
    if (!bookmarks.isEmpty()) {
        destPdf.setOutlines(bookmarks);
    }

    if (book.getInfo("author") != null)
        document.addAuthor(book.getInfo("author"));
    if (book.getInfo("title") != null)
        document.addTitle(book.getInfo("title"));
    if (book.getInfo("subtitle") != null)
        document.addSubject(book.getInfo("subtitle"));
    document.close();

    System.out.println("Merge complete. Saved to " + saveFile);
}

From source file:com.gp.cong.logisoft.lcl.report.LclVoyageNotificationPdfCreator.java

public void createPdf(String contextPath, String outputFileName, String unitssId, String voyContent)
        throws Exception {
    LclUnitSs lclUnitSs = new LclUnitSsDAO().findById(Long.parseLong(unitssId));
    String voyageNo = lclUnitSs.getLclSsHeader().getScheduleNo();
    String unitNo = lclUnitSs.getLclUnit().getUnitNo();
    document = new Document();
    document.setPageSize(PageSize.A4);/*ww  w.  j  a  v a  2  s.  c  o m*/
    document.setMargins(8, 2, 8, 8);
    pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(outputFileName));
    document.open();
    document.add(onStartPage(contextPath, voyageNo, unitNo, voyContent));
    document.add(voyInfo(lclUnitSs));
    document.add(unitInfo(lclUnitSs));
    document.add(dispoInfo(lclUnitSs));
    document.add(voyContent(voyContent));
    document.add(thankyouMsg(contextPath));
    document.close();
}

From source file:com.grant.report.BillPdf.java

public void printBill(PrintDetails printDetails) {
    try {/*from   w ww . jav  a2s  .co  m*/

        String newInvo = printDetails.getInvoiceNo().replaceAll("\\|", "_");
        FILE = "E:/" + newInvo + ".pdf";
        invoNo = printDetails.getInvoiceNo();

        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();
        addMetaData(document);
        addTitlePage(document, printDetails);
        //addContent(document);
        document.close();
    } catch (FileNotFoundException | DocumentException e) {
        e.printStackTrace();
    }

}