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

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

Introduction

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

Prototype


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

Source Link

Document

Use this method to get an instance of the PdfWriter.

Usage

From source file:com.tomasz.drag.triballocommanderro.controller.MakerPDF.java

public static void printToPDF(ArrayList<Person> workers, EventGig event) throws IOException, DocumentException {
    String filename = event.getName() + ".pdf";
    String path = event.getData() + " " + event.getName() + "//";

    Document document = new Document();
    // step 2//  w ww  .ja v a2s . c  om
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(path + filename));
    // step 3
    document.open();
    // step 4
    ColumnText column = new ColumnText(writer.getDirectContent());

    float[][] x = { { document.left(), document.left() + 230 }, { document.right() - 230, document.right() } };
    for (Person person : workers) {
        column.addElement(MakerPDF.createTable(person, event));
    }
    int count = 0;
    float height = 0;
    int status = ColumnText.START_COLUMN;
    while (ColumnText.hasMoreText(status)) {
        column.setSimpleColumn(x[count][0], document.bottom(), x[count][1], document.top() - height - 10);
        // render as much content as possible
        status = column.go();
        // go to a new page if you've reached the last column
        if (++count > 1) {
            count = 0;
            document.newPage();
        }
    }
    document.newPage();
    document.close();
}

From source file:com.tommontom.pdfsplitter.PdfMerge.java

public static void doMerge(java.util.List<InputStream> list, String[] imageList, String[] listWordExcels,
        OutputStream outputStream) throws DocumentException, IOException {
    Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    writer.setFullCompression();/*from   ww  w.j  a  v  a  2 s  .c  o m*/
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    Image img;
    for (InputStream in : list) {
        PdfReader reader = new PdfReader(in);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {

            document.newPage();
            //import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);
            //add the page to the destination pdf
            cb.addTemplate(page, 0, 0);
        }

    }
    for (int i = 0; i < imageList.length; i++) {
        document.newPage();
        if (imageList[i] != null) {
            img = Image.getInstance(String.format("%s", imageList[i]));
            Rectangle one = new Rectangle(img.getPlainWidth(), img.getPlainHeight());
            document.setPageSize(one);
            if (img.getScaledWidth() > img.getScaledHeight()) {
                img.rotate();
            }
            if (img.getScaledWidth() > 792 || img.getScaledHeight() > 792) {
                img.scaleToFit(792, 792);

            }
            img.setDpi(150, 150);
            document.add(img);
        }
    }
    for (int i = 0; i < listWordExcels.length; i++) {
        if (imageList[i] != null) {
            File input = new File(listWordExcels[i]);
            File output = new File(listWordExcels[i] + ".pdf");
            String outputS = listWordExcels[i] + ".pdf";
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(input, output);
            PdfReader readerWord = new PdfReader(outputS);
            PdfImportedPage page = writer.getImportedPage(readerWord, readerWord.getNumberOfPages());
            cb.addTemplate(page, 0, 0);
        }
    }

    outputStream.flush();
    document.close();
    outputStream.close();
}

From source file:com.udec.utilidades.PdfTable.java

public PdfTable(Periodo p, String codigo) {
    empleados = eC.findByList("codigo", Integer.parseInt(codigo));
    if (empleados != null && empleados.size() > 0) {
        documento = new Document(PageSize.LETTER, 80, 80, 75, 75);
        this.pe = p;
        String ruta = archivo.replace("PdfTabla", p.getNombre() + codigo);
        try {//from  w  w  w.j  ava2s  .com
            //Obtenemos la instancia del archivo a utilizar
            writer = PdfWriter.getInstance(documento, new FileOutputStream(ruta));
            documento.open();
        } catch (Exception ex) {
            ex.getMessage();
        }
        for (Empleado empleado : empleados) {
            nom = nC.findByList2("periodoIdperiodo", p, "empleadoCodigo", empleado);
            documento.newPage();
            createPdf(nom, p);

        }
        documento.close(); //Cerramos el documento
        writer.close(); //Cerramos writer
        try {
            File path = new File(ruta);
            Desktop.getDesktop().open(path);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } else {
        JOptionPane.showMessageDialog(null, "El cdigo del empleado ingresado no existe.", "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.udec.utilidades.PdfTable.java

public PdfTable(Periodo p) {
    documento = new Document(PageSize.LETTER, 80, 80, 75, 75);
    this.pe = p;//from w w w .  j ava 2  s . c o  m
    String ruta = archivo.replace("PdfTabla", p.getNombre());
    try {
        //Obtenemos la instancia del archivo a utilizar
        writer = PdfWriter.getInstance(documento, new FileOutputStream(ruta));
        documento.open();
    } catch (Exception ex) {
        ex.getMessage();
    }
    empleados = eC.findByList("estado", "ACTIVO");
    for (Empleado empleado : empleados) {
        nom = nC.findByList2("periodoIdperiodo", p, "empleadoCodigo", empleado);
        documento.newPage();
        createPdf(nom, p);

    }
    documento.close(); //Cerramos el documento
    writer.close(); //Cerramos writer
    try {
        File path = new File(ruta);
        Desktop.getDesktop().open(path);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.unicauca.coordinacionpis.managedbean.RegistroFormatoAController.java

public void agregarMetadatos() {
    // create document and writer
    Document document = new Document(PageSize.A4);
    PdfWriter writer;/*  w  ww  .  j  a  v a2 s  .com*/
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\aguaabril2016.pdf"));
        // add meta-data to pdf
        document.addAuthor("Memorynotfound");
        document.addCreationDate();
        document.addCreator("Memorynotfound.com");
        document.addTitle("Add meta data to PDF");
        document.addSubject("how to add meta data to pdf using itext");
        document.addKeywords(metadatosAnteproyectos.getTitulo() + "," + metadatosAnteproyectos.getProfesor());
        document.addLanguage(Locale.ENGLISH.getLanguage());
        document.addHeader("type", "tutorial, example");

        // add xmp meta data
        writer.createXmpMetadata();

        document.open();
        document.add(new Paragraph("Add meta-data to PDF using iText"));
        document.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(RegistroOfertaAcademicaController.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(RegistroOfertaAcademicaController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.VanLesh.macsv10.macs.Models.Pdf.java

License:GNU General Public License

public static void maker(Calculation calc) {
    try {/*from   w  w  w .  j  av  a2 s . co m*/
        File pdfFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Report.pdf");
        Document doc = new Document();
        PdfWriter.getInstance(doc, new FileOutputStream(pdfFile));
        doc.open();
        addMetaData(doc, calc);
        addContent(doc, calc);
        doc.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.vectorprint.report.itext.BaseReportGenerator.java

License:Open Source License

/**
 * prepare the report, call {@link #continueOnDataCollectionMessages(com.vectorprint.report.data.DataCollectionMessages, com.itextpdf.text.Document)
 * }//from  ww  w  .j  av  a2s  .c  om
 * and when this returns true call {@link #createReportBody(com.itextpdf.text.Document, com.vectorprint.report.data.ReportDataHolder, com.itextpdf.text.pdf.PdfWriter)
 * }. When a Runtime, VectorPrint, IO and DocumentException occurs {@link #handleException(java.lang.Exception, java.io.OutputStream)
 * } will be called.
 *
 * @param data
 * @param outputStream
 * @return 0 or {@link #ERRORINREPORT}
 * @throws com.vectorprint.VectorPrintException
 */
@Override
public final int generate(RD data, OutputStream out) throws VectorPrintException {
    try {
        DocumentStyler ds = stylerFactory.getDocumentStyler();
        ds.setReportDataHolder(data);

        wasDebug = getSettings().getBooleanProperty(Boolean.FALSE, DEBUG);
        if (ds.getValue(DocumentSettings.TOC, Boolean.class)) {
            out = new TocOutputStream(out, bufferSize, this);
            getSettings().put(DEBUG, Boolean.FALSE.toString());
        }

        if (ds.isParameterSet(DocumentSettings.KEYSTORE)) {
            out = new SigningOutputStream(out, bufferSize, this);
        }

        document = new VectorPrintDocument(eventHelper, stylerFactory, styleHelper);
        writer = PdfWriter.getInstance(document, out);
        styleHelper.setVpd((VectorPrintDocument) document);
        ((VectorPrintDocument) document).setWriter(writer);

        eventHelper.setReportDataHolder(data);
        writer.setPageEvent(eventHelper);
        stylerFactory.setDocument(document, writer);
        stylerFactory.setImageLoader(elementProducer);
        stylerFactory.setLayerManager(elementProducer);

        StylerFactoryHelper.initStylingObject(ds, writer, document, this, elementProducer, settings);
        ds.loadFonts();
        styleHelper.style(document, data, StyleHelper.toCollection(ds));
        document.open();
        if (ds.canStyle(document) && ds.shouldStyle(data, document)) {
            ds.styleAfterOpen(document, data);
        }

        // data from the data collection phase doesn't have to be present
        if (data == null || continueOnDataCollectionMessages(data.getMessages(), document)) {
            createReportBody(document, data, writer);
            /*
             * when using queueing we may have run into failures in the data collection thread
             */
            if (data != null && !data.getData().isEmpty()) {
                Object t = data.getData().poll();
                if (t instanceof Throwable) {
                    throw new VectorPrintException((Throwable) t);
                }
            }
        }
        eventHelper.setLastPage(writer.getCurrentPageNumber());

        if (getSettings().getBooleanProperty(false, DEBUG)) {
            eventHelper.setLastPage(writer.getCurrentPageNumber());
            document.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            document.setMargins(5, 5, 5, 5);
            document.newPage();
            eventHelper.setDebugHereAfter(true);
            if (!ds.getValue(DocumentSettings.TOC, Boolean.class)) {
                DebugHelper.appendDebugInfo(writer, document, settings, stylerFactory);
            }
        }

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

        return 0;
    } catch (RuntimeException | DocumentException | VectorPrintException | IOException e) {
        return handleException(e, out);
    }
}

From source file:com.vectorprint.report.itext.TocOutputStream.java

License:Open Source License

@Override
public void secondPass(InputStream firstPass, OutputStream orig) throws IOException {
    PdfReader reader = null;/* ww  w.j a v  a2  s  . c o m*/
    VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument();
    try {
        reader = new PdfReader(firstPass);
        prepareToc();
        // init fresh components for second pass styling
        StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance();
        StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings());
        _stylerFactory.setLayerManager(outer.getElementProducer());
        _stylerFactory.setImageLoader(outer.getElementProducer());
        outer.getStyleHelper().setStylerFactory(_stylerFactory);
        EventHelper event = outer.getEventHelper().getClass().newInstance();
        event.setItextStylerFactory(_stylerFactory);
        event.setElementProvider(outer.getElementProducer());
        ((DefaultElementProducer) outer.getElementProducer()).setPh(event);
        Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper());
        PdfWriter w = PdfWriter.getInstance(d, orig);
        w.setPageEvent(event);
        outer.getStyleHelper().setVpd((VectorPrintDocument) d);
        _stylerFactory.setDocument(d, w);
        DocumentStyler ds = _stylerFactory.getDocumentStyler();
        outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds));
        d.open();
        ds.styleAfterOpen(d, null);
        List outline = SimpleBookmark.getBookmark(reader);
        if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
            if (outline != null) {
                int cur = w.getCurrentPageNumber();
                SimpleBookmark.shiftPageNumbers(outline, cur, null);
            }
            d.newPage();
        }
        outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString());
        for (int p = 1; p <= reader.getNumberOfPages(); p++) {
            Image page = Image.getInstance(w.getImportedPage(reader, p));
            page.setAbsolutePosition(0, 0);
            d.setPageSize(page);
            d.newPage();
            Chunk i = new Chunk(" ");
            if (vpd.getToc().containsKey(p)) {
                Section s = null;
                for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) {
                    if (e.getKey() == p) {
                        s = e.getValue().get(0);
                        break;
                    }
                }
                i.setLocalDestination(s.getTitle().getContent());
            }
            d.add(i);
            w.getDirectContent().addImage(page);
            w.freeReader(reader);
        }
        if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
        }
        w.setOutlines(outline);
        if (outer.isWasDebug()) {
            event.setLastPage(outer.getWriter().getCurrentPageNumber());
            d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            d.setMargins(5, 5, 5, 5);
            d.newPage();
            outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString());
            event.setDebugHereAfter(true);
            DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory);
        }
        d.close();
    } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) {
        throw new VectorPrintRuntimeException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.vectorprint.vectorprintreportgui.Controller.java

License:Open Source License

private void importStyle(ParsingProperties settings) throws DocumentException, VectorPrintException {
    clear(null);//ww  w  . j a v a 2  s  .  c om
    Boolean preAndPost = settings.getBooleanProperty(true, DefaultStylerFactory.PREANDPOSTSTYLE);
    // set to false when importing to prevent all pre and post stylers to be added to regulerar style classes
    settings.put(DefaultStylerFactory.PREANDPOSTSTYLE, Boolean.FALSE.toString());
    DefaultStylerFactory sf = new DefaultStylerFactory();
    StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(sf, settings);
    Document d = new Document();
    PdfWriter w = PdfWriter.getInstance(d, new ByteArrayOutputStream(0));
    w.setPageEvent(new EventHelper());
    sf.setDocument(d, w);

    for (Map.Entry<String, String[]> e : settings.entrySet()) {
        commentsBefore.put(e.getKey(), settings.getCommentBeforeKey(e.getKey()));
        if (ReportConstants.DOCUMENTSETTINGS.equals(e.getKey())) {
            stylingConfig.put(e.getKey(), new ArrayList<>(1));
            stylingConfig.get(e.getKey()).add(sf.getDocumentStyler());
            pdf1a.setSelected(sf.getDocumentStyler().getValue(DocumentSettings.PDFA, Boolean.class));
            toc.setSelected(sf.getDocumentStyler().getValue(DocumentSettings.TOC, Boolean.class));
        } else if (ViewHelper.isStyler(e.getKey(), settings)) {
            stylingConfig.put(e.getKey(), new ArrayList<>(3));
            try {
                List<BaseStyler> l = sf.getStylers(e.getKey());
                stylingConfig.get(e.getKey()).addAll(l);
                getConditions(l);
                getDefaults(l, settings);
            } catch (VectorPrintException ex) {
                ViewHelper.toError(ex, error);
            }
        } else if (!ViewHelper.isCondition(e.getKey(), settings)) {
            if (DefaultStylerFactory.PREANDPOSTSTYLE.equals(e.getKey())) {
                prepost.setSelected(preAndPost);
                extraSettings.put(e.getKey(), preAndPost.toString());
            } else {
                if (ReportConstants.DEBUG.equals(e.getKey())) {
                    debug.setSelected(Boolean.valueOf(e.getValue()[0]));
                } else if (ReportConstants.PRINTFOOTER.equals(e.getKey())) {
                    footer.setSelected(Boolean.valueOf(e.getValue()[0]));
                }
                extraSettings.put(e.getKey(), e.getValue()[0]);
            }
        }
    }
    for (Iterator it = extraSettings.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> e = (Map.Entry<String, String>) it.next();
        if (processed.contains(e.getKey())) {
            it.remove();
        }
    }
    // check conditions not referenced
    settings.entrySet().stream().forEach((e) -> {
        if (ViewHelper.isCondition(e.getKey(), settings)) {
            Logger.getLogger(Controller.class.getName())
                    .warning(String.format("unreferenced conditions for key: %s", e.getKey()));
            List<StylingCondition> conditions;
            try {
                conditions = sf.getConditions(e.getKey());
            } catch (VectorPrintException ex) {
                throw new VectorPrintRuntimeException(ex);
            }
            stylingConfig.put(e.getKey(), new ArrayList<>(conditions.size()));
            stylingConfig.get(e.getKey()).addAll(conditions);
        }
    });
    commentsAfter.addAll(settings.getTrailingComment());
    ViewHelper.notify("ok", "import complete", "you can now adapt and (re)build your stylesheet");
}

From source file:com.verbox.PrintHtml.java

public static void RenderPDF_img_too(String inpHtml) throws FileNotFoundException, ParserConfigurationException,
        SAXException, IOException, DocumentException, PrinterException {
    try {/*  w  w  w  . j a  v  a2 s .  c om*/
        fullhtml = inpHtml;
        String replaceAll = fullhtml.replaceAll("../../image/", "");
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf"));
        // step 3
        document.open();
        // step 4
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        InputStream is = new ByteArrayInputStream(replaceAll.getBytes(StandardCharsets.UTF_8));
        worker.parseXHtml(writer, document, is, Charset.forName("UTF-8"));
        // step 5
        document.close();
        PreImgPrint();

    } catch (DocumentException | IOException E) {
        JOptionPane.showMessageDialog(null, "Exeption on print or prepare image " + E);
    }
}