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.unsa.view.MainView.java

License:Creative Commons License

private void DocConverterPDF(File file1) {
    NPOIFSFileSystem fs = null;/*from w w  w.j av  a 2  s  .c  o  m*/
    com.lowagie.text.Document document = new com.lowagie.text.Document();

    try {
        System.out.println(file1.getAbsolutePath());
        fs = new NPOIFSFileSystem(new FileInputStream(file1.getAbsolutePath()));
        HWPFDocument doc = new HWPFDocument(fs.getRoot());
        WordExtractor we = new WordExtractor(doc);
        String output = file1.getAbsolutePath().substring(0, file1.getAbsolutePath().length() - 3);
        OutputStream fileout = new FileOutputStream(new File(output + "pdf"));

        PdfWriter writer = PdfWriter.getInstance(document, fileout);

        Range range = doc.getRange();
        document.open();
        writer.setPageEmpty(true);
        document.newPage();
        writer.setPageEmpty(true);

        String[] paragraphs = we.getParagraphText();
        for (int i = 0; i < paragraphs.length; i++) {

            org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
            paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
            document.add(new Paragraph(paragraphs[i]));
        }

    } catch (Exception e) {

        e.printStackTrace();
    } finally {

        document.close();
    }

}

From source file:com.virtusa.akura.student.controller.MessageBoardController.java

License:Open Source License

/**
 * Merge many pdf files into one file.//from w w w .jav  a 2  s  .  c o m
 *
 * @param streamOfPDFFiles - a list of inputStreams
 * @param outputStream - an instance of outputStream
 * @param paginate - a boolean
 * @throws AkuraAppException - The exception details that occurred when processing
 */
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate)
        throws AkuraAppException {

    final int fontSize = 8, leftRightAlignment = 8;
    final int min = 0;
    final int max = 5;
    final int size = 300;
    final int xAxis = -150;
    final int pageHeight = 550;
    final int pageHieghtfromBottom = 16;
    final int pageRecHeight = 580;
    final int recHeightFromBottom = 14;
    Document document = new Document(PageSize.A4);
    try {
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the output stream
        PdfWriter writer = null;
        BaseFont bf = null;
        try {
            writer = PdfWriter.getInstance(document, outputStream);

            document.open();

            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

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

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

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, fontSize);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + AkuraWebConstant.REPORT_GPL, size,
                            max, min);
                    cb.newlineText();
                    cb.endText();

                    if (currentPageNumber != 2) {
                        int pageNo = currentPageNumber;
                        if (currentPageNumber != 1) {
                            pageNo = currentPageNumber - 1;
                        }

                        // write the page number inside a rectangle.
                        cb.fillStroke();
                        cb.rectangle(leftRightAlignment, recHeightFromBottom, pageRecHeight,
                                leftRightAlignment);
                        cb.beginText();
                        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, PAGE + pageNo, pageHeight,
                                pageHieghtfromBottom, 0);
                        cb.endText();
                        cb.stroke();
                    }
                }
            }
            pageOfCurrentReaderPDF = 0;
        }

        outputStream.flush();

        document.close();

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:Controleur.CtrlImprimerOrdonnance.java

public void RemplirOrdonnance() {
    ResultSet res;/*from   ww w .  j  a v a2s  .c o  m*/
    String nomEtablissement = "";
    String adresseEtablissement = "";
    int telEtablissement = 0;
    String nomPatient = "";
    String prenomPatient = "";
    String dateNaissPatient = null;
    String traitement = "";
    Etablissement etab = new Etablissement();
    try {
        res = etab.getEtablissement();
        nomEtablissement = res.getString("nomEtab");
        adresseEtablissement = res.getString("adresseEtab");
        telEtablissement = res.getInt("telEtab");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "erreur \n" + e.getMessage());
    }
    Medecin med1 = new Medecin();
    Medecin med2 = med1.getMedecinById(Fen.getIdm());
    String nomMedecin = med2.getNomMedecin();
    String prenomMedecin = med2.getPrenomMedecin();
    String specialiteMedecin = med2.getSpecialite();
    Patient patient = new Patient();
    res = patient.getPatient(Fen.getIdp());
    try {
        res.next();
        nomPatient = res.getString("nomPatient");
        prenomPatient = res.getString("prenomPatient");
        dateNaissPatient = res.getString("dateNaissance");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "erreur \n" + e.getMessage());
    }

    traitement = Fen.getTxtTraitement().getText();

    Document document = new Document(PageSize.A4);
    try {
        PdfWriter.getInstance(document, new FileOutputStream("./ordonnance.pdf"));
        document.open();
        Date d = new Date();
        Paragraph paragraph = new Paragraph(d.toLocaleString(),
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setAlignment(Element.ALIGN_RIGHT);
        paragraph.setIndentationRight(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Dr " + nomMedecin + " " + prenomMedecin,
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("SPECIALISTE EN " + specialiteMedecin);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(nomEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(adresseEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Tl : " + telEtablissement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("                      ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("nom & prenom :" + nomPatient + " " + prenomPatient,
                FontFactory.getFont(FontFactory.COURIER, 20, Font.BOLD));
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("Ne(e) le :" + dateNaissPatient);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph("                       ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);

        Chunk chunk = new Chunk("Ordonnance", FontFactory.getFont(FontFactory.COURIER, 30, Font.BOLD));
        chunk.setUnderline(Color.BLACK, 3.0f, 0.0f, 0.0f, -0.2f, PdfContentByte.LINE_CAP_BUTT);
        paragraph = new Paragraph();
        paragraph.setAlignment(Element.ALIGN_CENTER);
        paragraph.add(chunk);
        document.add(paragraph);

        paragraph = new Paragraph("                       ");
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);
        paragraph = new Paragraph(traitement);
        paragraph.setIndentationLeft(50f);
        document.add(paragraph);

        Runtime r = Runtime.getRuntime();
        r.exec("cmd /C ./ordonnance.pdf");
    } catch (DocumentException de) {
        de.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    document.close();
}

From source file:convert.Convertings.java

public void convertTif2PDF(String tifPath, String path) {
    System.out.println("one");
    String arg[] = { tifPath };//from w w w.j  av  a  2  s  . c  o m
    System.out.println("one2");
    if (arg.length < 1) {
        System.out.println("Usage: Tiff2Pdf file1.tif [file2.tif ... fileN.tif]");
        System.exit(1);
    }
    String tiff;
    String pdf;
    System.out.println("two");
    for (int i = 0; i < arg.length; i++) {
        tiff = arg[i];
        pdf = path + ".pdf";
        Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
            int pages = 0;
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            RandomAccessFileOrArray ra = null;
            int comps = 0;
            try {
                ra = new RandomAccessFileOrArray(tiff);
                comps = TiffImage.getNumberOfPages(ra);
            } catch (Throwable e) {
                System.out.println("Exception in " + tiff + " " + e.getMessage());
                continue;
            }
            System.out.println("Processing: " + tiff);
            for (int c = 0; c < comps; ++c) {
                try {
                    Image img = TiffImage.getTiffImage(ra, c + 1);
                    if (img != null) {
                        System.out.println("page " + (c + 1));
                        System.out.println("img.getDpiX() : " + img.getDpiX());
                        System.out.println("img.getDpiY() : " + img.getDpiY());
                        img.scalePercent(6200f / img.getDpiX(), 6200f / img.getDpiY());
                        //img.scalePercent(img.getDpiX(), img.getDpiY());
                        //document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
                        img.setAbsolutePosition(0, 0);
                        cb.addImage(img);
                        document.newPage();
                        ++pages;
                    }
                } catch (Throwable e) {
                    System.out.println("Exception " + tiff + " page " + (c + 1) + " " + e.getMessage());
                }
            }
            ra.close();
            document.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("done");
    }
}

From source file:corner.orm.tapestry.pdf.service.PdfResponseBuilder.java

License:Apache License

public void renderResponse(IRequestCycle cycle) throws IOException {
    // ??/*from   w ww  .  j  a v a2s  .  c o  m*/
    IPage pdfPage = cycle.getPage();
    // PDF.
    OutputStream os = response.getOutputStream(IPdfPage.CONTENT_TYPE);
    // PDF
    _doc = new Document();

    // PDF Writer
    PdfWriter pdfWriter = null;
    try {

        // PDF writer.
        pdfWriter = PdfWriter.getInstance(_doc, os);

        if (pdfPage instanceof IPdfPage) { // PDF Page?.
            // ?
            PdfOutputPageEvent event = new PdfOutputPageEvent((IPdfPage) pdfPage);
            pdfWriter.setPageEvent(event);
            // Pdf writer?.
            _writer = new PdfWriterDelegate(pdfWriter);
            // pdf
            _doc.open();

            // PDF Writer??.
            cycle.setAttribute(PDF_DOCUMENT_ATTRIBUTE_NAME, _doc);

            // PDF?
            cycle.renderPage(this);

            // PDF??.
            cycle.removeAttribute(PDF_DOCUMENT_ATTRIBUTE_NAME);

            // PDF.
            _doc.close();

        } else if (pdfPage instanceof org.apache.tapestry.pages.Exception) { // ??.

            ExceptionDescription[] exceptions = (ExceptionDescription[]) PropertyUtils.read(pdfPage,
                    "exceptions");
            if (exceptions == null) {
                throw new ApplicationRuntimeException("UNKOWN Exception!");

            } else { // ???.
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < exceptions.length; i++) {
                    sb.append(exceptions[i].getMessage()).append("\n");
                    ExceptionProperty[] pros = exceptions[i].getProperties();
                    for (ExceptionProperty pro : pros) {
                        sb.append(pro.getName()).append(" ").append(pro.getValue()).append("\n");
                    }
                    String[] traces = exceptions[i].getStackTrace();
                    if (traces == null) {
                        continue;
                    }
                    for (int j = 0; j < traces.length; j++) {
                        sb.append(traces[j]).append("\n");
                    }
                }
                throw new Exception(sb.toString());
            }
        }
    } catch (Throwable e) { // ?.
        if (pdfWriter == null) {
            e.printStackTrace();
            return;
        }
        if (!_doc.isOpen()) {
            _doc.open();
        }
        pdfWriter.setPageEvent(null);

        _doc.newPage();

        // PDF???SO COOL! :)
        try {
            _doc.add(new Phrase("pdf?:", PdfUtils.createSongLightFont(12)));
            _doc.add(new Paragraph(e.getMessage()));
            _doc.add(new Paragraph(fetchStackTrace(e)));
            _doc.close();
        } catch (DocumentException e1) {
            throw new ApplicationRuntimeException(e1);
        }

    }
}

From source file:Cotizacion.ExportarPDF.java

public static void guardarPDF() {
    obtenerNumeroCotizacion();/*w  ww  .  java 2  s .  c  o  m*/
    nombrePDF = PanelCotizacion.labelObtenerNombreCliente.getText();
    fecha = PanelCotizacion.labelObtenerFecha.getText();
    try {

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(numeroC + " " + nombrePDF + " " + fecha + ".pdf"));
        document.open();

        agregarMetaDatos(document);

        agregarContenido(document);

        document.close();

        JOptionPane.showMessageDialog(null, "Se ha generado el archivo PDF " + nombrePDF, "Atencin:",
                JOptionPane.WARNING_MESSAGE);
        System.out.println("Se ha generado el PDF: " + nombrePDF + ".pdf");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:CPS.Core.TODOLists.PDFExporter.java

License:Open Source License

private Document prepareDocument(String filename, final String title, final String author, final String creator,
        final Rectangle pageSize) {

    System.out.println("DEBUG(PDFExporter): Creating document: " + filename);

    Document d = new Document();

    d.setPageSize(pageSize);//from   www  . j a va2 s.c  om
    // TODO alter page orientation?  maybe useful for seed order worksheet

    d.addTitle(title);
    d.addAuthor(author);
    //        d.addSubject( );
    //        d.addKeywords( );
    d.addCreator(creator);

    // left, right, top, bottom - scale in points (~72 points/inch)
    d.setMargins(35, 35, 35, 44);

    try {
        PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(filename));
        // add header and footer
        writer.setPageEvent(new PdfPageEventHelper() {
            public void onEndPage(PdfWriter writer, Document document) {
                try {
                    Rectangle page = document.getPageSize();

                    PdfPTable head = new PdfPTable(3);
                    head.getDefaultCell().setBorderWidth(0);
                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    head.addCell(new Phrase(author, fontHeadFootItal));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    head.addCell(new Phrase(title, fontHeadFootReg));

                    head.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    head.addCell("");

                    head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    head.writeSelectedRows(0, -1, document.leftMargin(),
                            page.getHeight() - document.topMargin() + head.getTotalHeight(),
                            writer.getDirectContent());

                    PdfPTable foot = new PdfPTable(3);

                    foot.getDefaultCell().setBorderWidth(0);
                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_LEFT);
                    foot.addCell(new Phrase(creator, fontHeadFootItal));

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                    foot.addCell("");

                    foot.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_RIGHT);
                    foot.addCell(new Phrase("Page " + document.getPageNumber(), fontHeadFootReg));

                    foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                    foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                            writer.getDirectContent());
                } catch (Exception e) {
                    throw new ExceptionConverter(e);
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

    return d;
}

From source file:cz.incad.kramerius.pdf.impl.FirstPageAsImagePDFServiceImpl.java

License:Open Source License

public void insertImage(PreparedDocument rdoc, OutputStream os, File imageFile)
        throws DocumentException, IOException, MalformedURLException, BadElementException {
    Document doc = DocumentUtils.createDocument(rdoc);

    PdfWriter writer = PdfWriter.getInstance(doc, os);
    doc.open();/*from   w  w  w . ja va2  s  .c  o m*/

    insertImageFromURL(doc, 1.0f, imageFile.toURI().toURL().toString(), ImageMimeType.PNG);

    doc.close();
    os.flush();
}

From source file:cz.incad.kramerius.pdf.impl.FirstPagePDFServiceImpl.java

License:Open Source License

@Override
public void selection(PreparedDocument rdoc, OutputStream os, String[] pids, FontMap fontMap) {
    try {//from ww  w  .  j ava  2  s.  co  m

        Document doc = DocumentUtils.createDocument(rdoc);
        PdfWriter writer = PdfWriter.getInstance(doc, os);
        doc.open();
        String itextCommands = templateSelection(rdoc, pids);
        renderFromTemplate(rdoc, doc, writer, fontMap, new StringReader(itextCommands));

        doc.close();
        os.flush();
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (InstantiationException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (IllegalAccessException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (SAXException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (DocumentException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (XPathExpressionException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:cz.incad.kramerius.pdf.impl.FirstPagePDFServiceImpl.java

License:Open Source License

@Override
public void parent(PreparedDocument rdoc, OutputStream os, ObjectPidsPath path, FontMap fontMap) {
    try {//w w  w  .j  a va  2s .c om

        Document doc = DocumentUtils.createDocument(rdoc);

        PdfWriter writer = PdfWriter.getInstance(doc, os);
        doc.open();

        String itextCommands = templateParent(rdoc, path);

        renderFromTemplate(rdoc, doc, writer, fontMap, new StringReader(itextCommands));

        doc.close();
        os.flush();
    } catch (DocumentException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (InstantiationException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (IllegalAccessException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (SAXException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (XPathExpressionException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    } catch (JAXBException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }

}