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

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

Introduction

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

Prototype

public void setPdfVersion(final PdfName version) 

Source Link

Usage

From source file:com.havoc.hotel.util.BookingPdf.java

public static String generateBookingPDF(Booking booking)
        throws DocumentException, FileNotFoundException, IOException {
    Document document = new Document(PageSize.A4);
    String bookingname = booking.getFirstName() + " " + booking.getLastName();
    document.addHeader("HOTEL HAVOC", "Hotel havoc Booking confirmation");
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(FILE + "Booking" + "" + booking.getCustomer().getFirstName() + ".pdf "));
    writer.setViewerPreferences(PdfWriter.PageModeUseOC);
    writer.setPdfVersion(PdfWriter.VERSION_1_7);
    document.open();//from w w  w  .  j a  v a  2 s .co  m
    String html = htmlTemplate(booking);

    List unorderedList = new List(List.UNORDERED);

    unorderedList.add(new ListItem("Name       :" + booking.getFirstName() + " " + booking.getLastName()));
    //        unorderedList.add(new ListItem("Room Price :" + booking.getRoom().getRoomPrice()));
    unorderedList.add(new ListItem("Total Price :" + booking.getTotalPrice()));
    unorderedList.add(new ListItem("check in   :" + booking.getCheckinDate()));
    unorderedList.add(new ListItem("Total Nights:" + booking.getTotalNights()));
    unorderedList.add(new ListItem("check out  :" + booking.getCheckoutDate()));
    unorderedList.add(new ListItem("Booked By  :" + booking.getCustomer().getUsername()));

    document.add(unorderedList);
    document.close();
    return bookingname;

}

From source file:com.vectorprint.report.itext.style.stylers.DocumentSettings.java

License:Open Source License

/**
 * called as the last step from {@link #style(java.lang.Object, java.lang.Object) }, calls {@link #builtInFontHack()
 * } which is necessary when creating PDF/X-1a with iText.
 *
 * @param writer/*ww w .  j  a  v  a2  s.c o  m*/
 * @throws IOException
 * @throws DocumentException
 * @throws VectorPrintException
 */
protected void pdfA1A(PdfWriter writer) throws IOException, DocumentException, VectorPrintException {
    builtInFontHack();
    writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
    writer.setTagged();
    writer.setPDFXConformance(PdfWriter.PDFX1A2001);
}

From source file:cz.muni.pdfjbim.PdfImageProcessor.java

License:Apache License

/**
 * replace images by they recompressed version according to JBIG2 standard
 * positions and image data given in imagesData
 * @param pdfName represents name of original PDF file
 * @param os represents output stream for writing changed PDF file
 * @param imagesData contains compressed images according to JBIG2 standard and informations about them
 * @throws PdfRecompressionException if version of PDF is lower than 1.4 or was catch DocumentException or IOException
 *///from   w  ww.  j av a2  s .co  m
public void replaceImageUsingIText(String pdfName, OutputStream os, Jbig2ForPdf imagesData)
        throws PdfRecompressionException {
    if (pdfName == null) {
        throw new NullPointerException("pdfName");
    }

    if (os == null) {
        throw new NullPointerException("os");
    }

    if (imagesData == null) {
        throw new NullPointerException("imagesData is null => nothing to recompress");
    }

    Map<PdfObjId, PdfImage> jbig2Images = imagesData.getMapOfJbig2Images();

    PdfReader pdf;
    PdfStamper stp = null;
    try {
        pdf = new PdfReader(pdfName);
        stp = new PdfStamper(pdf, os);
        PdfWriter writer = stp.getWriter();

        int version;
        if ((version = Integer.parseInt(String.valueOf(pdf.getPdfVersion()))) < 4) {
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
        }

        Iterator itImages = jbig2Images.values().iterator();
        String key;
        if (itImages.hasNext()) {
            PdfImage myImg = (PdfImage) itImages.next();
            key = myImg.getPdfImageInformation().getKey();
        } else {
            key = "im0";
        }

        for (int pageNum = 1; pageNum <= pdf.getNumberOfPages(); pageNum++) {

            PdfDictionary pg = pdf.getPageN(pageNum);
            PdfDictionary resPg = (PdfDictionary) PdfReader.getPdfObject(pg.get(PdfName.RESOURCES));

            PdfDictionary xobjResPg = (PdfDictionary) PdfReader.getPdfObject(resPg.get(PdfName.XOBJECT));

            PdfObject obj = null;
            if (xobjResPg != null) {
                for (Iterator it = xobjResPg.getKeys().iterator(); it.hasNext();) {
                    PdfObject pdfObjIndirect = xobjResPg.get((PdfName) it.next());
                    if (pdfObjIndirect.isIndirect()) {
                        PdfDictionary pdfObj2 = (PdfDictionary) PdfReader.getPdfObject(pdfObjIndirect);
                        PdfDictionary xobj2Res = (PdfDictionary) PdfReader
                                .getPdfObject(pdfObj2.get(PdfName.RESOURCES));
                        if (xobj2Res != null) {
                            for (Iterator it2 = xobj2Res.getKeys().iterator(); it2.hasNext();) {
                                PdfObject resObj = xobj2Res.get((PdfName) it2.next());
                            }
                            PdfDictionary xobj = (PdfDictionary) PdfReader
                                    .getPdfObject(xobj2Res.get(PdfName.XOBJECT));
                            if (xobj == null) {
                                continue;
                            }
                            obj = xobj.get(new PdfName(key));
                        } else {
                            obj = xobjResPg.get(new PdfName(key));
                            if (obj == null) {
                                obj = pdfObjIndirect;
                            }
                        }
                    }
                }
            }

            if ((obj != null) && (obj.isIndirect())) {

                PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj);
                if (tg == null) {
                    continue;
                }
                PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE));
                if (PdfName.IMAGE.equals(type)) {
                    PRIndirectReference ref = (PRIndirectReference) obj;
                    PdfObjId imId = new PdfObjId(ref.getNumber(), ref.getGeneration());
                    PdfImage jbImage = jbig2Images.get(imId);
                    if (jbImage == null) {
                        continue;
                    }
                    PdfImageInformation jbImageInfo = jbImage.getPdfImageInformation();
                    Image img = Image.getInstance(jbImageInfo.getWidth(), jbImageInfo.getHeight(),
                            jbImage.getImageData(), imagesData.getGlobalData());

                    PdfReader.killIndirect(obj);
                    Image maskImage = img.getImageMask();

                    if (maskImage != null) {
                        writer.addDirectImageSimple(maskImage);
                    }
                    writer.addDirectImageSimple(img, (PRIndirectReference) obj);
                }
            }
        }
        stp.close();
    } catch (IOException ioEx) {
        throw new PdfRecompressionException(ioEx);
    } catch (DocumentException dEx) {
        throw new PdfRecompressionException(dEx);
    } finally {
        Tools.deleteFilesFromList(imagesData.getJbFiles().toArray(new File[0]));
    }
}

From source file:cz.muni.pdfjbim.PdfImageReplacer.java

License:Apache License

/**
 * replace images by they recompressed version according to JBIG2 standard positions and image
 * data given in imagesData/*  www  .  j ava2s . c om*/
 *
 * @param originalPdf represents name of original PDF file
 * @param os represents output stream for writing changed PDF file
 * @param imagesData contains compressed images according to JBIG2 standard and informations
 * about them
 * @throws PdfRecompressionException if version of PDF is lower than 1.4 or was catch
 * DocumentException or IOException
 */
public void replaceImageUsingIText(InputStream originalPdf, OutputStream os, List<Jbig2ForPdf> imagesDataList)
        throws PdfRecompressionException {
    if (originalPdf == null) {
        throw new NullPointerException("pdfName");
    }

    if (os == null) {
        throw new NullPointerException("os");
    }

    if (imagesDataList == null) {
        throw new NullPointerException("imagesData is null => nothing to recompress");
    }

    log.info("Replacing old images in PDF with their equivalent encoded according to standard JBIG2");
    PdfReader pdf;
    PdfStamper stp = null;
    try {
        pdf = new PdfReader(originalPdf);
        stp = new PdfStamper(pdf, os);
        PdfWriter writer = stp.getWriter();

        int version;
        if ((version = Integer.parseInt(String.valueOf(pdf.getPdfVersion()))) < 4) {
            log.debug("PDF version of original PDF was {} => changing to PDF version 1.4", pdf.getPdfVersion());
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_4);
        }

        for (Jbig2ForPdf imagesData : imagesDataList) {

            Map<PdfObjId, PdfImage> jbig2Images = imagesData.getMapOfJbig2Images();

            Iterator itImages = jbig2Images.values().iterator();
            String key;
            if (itImages.hasNext()) {
                PdfImage myImg = (PdfImage) itImages.next();
                key = myImg.getPdfImageInformation().getKey();
            } else {
                key = "im0";
            }

            for (int pageNum = 1; pageNum <= pdf.getNumberOfPages(); pageNum++) {

                PdfDictionary pg = pdf.getPageN(pageNum);
                PdfDictionary resPg = (PdfDictionary) PdfReader.getPdfObject(pg.get(PdfName.RESOURCES));

                PdfDictionary xobjResPg = (PdfDictionary) PdfReader.getPdfObject(resPg.get(PdfName.XOBJECT));

                PdfObject obj = null;
                if (xobjResPg != null) {
                    for (Iterator it = xobjResPg.getKeys().iterator(); it.hasNext();) {
                        PdfObject pdfObjIndirect = xobjResPg.get((PdfName) it.next());
                        if (pdfObjIndirect.isIndirect()) {
                            PdfDictionary pdfObj2 = (PdfDictionary) PdfReader.getPdfObject(pdfObjIndirect);
                            PdfDictionary xobj2Res = (PdfDictionary) PdfReader
                                    .getPdfObject(pdfObj2.get(PdfName.RESOURCES));
                            if (xobj2Res != null) {
                                for (Iterator it2 = xobj2Res.getKeys().iterator(); it2.hasNext();) {
                                    PdfObject resObj = xobj2Res.get((PdfName) it2.next());
                                }
                                PdfDictionary xobj = (PdfDictionary) PdfReader
                                        .getPdfObject(xobj2Res.get(PdfName.XOBJECT));
                                if (xobj == null) {
                                    continue;
                                }
                                obj = xobj.get(new PdfName(key));
                            } else {
                                obj = xobjResPg.get(new PdfName(key));
                                if (obj == null) {
                                    obj = pdfObjIndirect;
                                }
                            }
                        }
                    }
                }

                if ((obj != null) && (obj.isIndirect())) {

                    PdfDictionary tg = (PdfDictionary) PdfReader.getPdfObject(obj);
                    if (tg == null) {
                        continue;
                    }
                    PdfName type = (PdfName) PdfReader.getPdfObject(tg.get(PdfName.SUBTYPE));
                    if (PdfName.IMAGE.equals(type)) {
                        PRIndirectReference ref = (PRIndirectReference) obj;
                        PdfObjId imId = new PdfObjId(ref.getNumber(), ref.getGeneration());
                        PdfImage jbImage = jbig2Images.get(imId);
                        if (jbImage == null) {
                            continue;
                        }

                        log.debug("Replacing image {}", jbImage);
                        PdfImageInformation jbImageInfo = jbImage.getPdfImageInformation();
                        Image img = Image.getInstance(jbImageInfo.getWidth(), jbImageInfo.getHeight(),
                                jbImage.getImageData(), imagesData.getGlobalData());

                        PdfReader.killIndirect(obj);
                        Image maskImage = img.getImageMask();

                        if (maskImage != null) {
                            writer.addDirectImageSimple(maskImage);
                        }
                        writer.addDirectImageSimple(img, (PRIndirectReference) obj);
                    }
                }
            }
        }
    } catch (IOException ioEx) {
        throw new PdfRecompressionException(ioEx);
    } catch (DocumentException dEx) {
        throw new PdfRecompressionException(dEx);
    } finally {
        log.debug("Deleting temporary files created during process of PDF recompression");
        for (Jbig2ForPdf imagesData : imagesDataList) {
            Tools.deleteFilesFromList(imagesData.getJbFiles().toArray(new File[0]));
        }
        try {
            if (stp != null) {
                stp.close();
            }
        } catch (DocumentException ex) {
            log.error("Exception thrown while closing stream", ex);
        } catch (IOException ex) {
            log.error("Exception thrown while closing stream", ex);
        }
    }

}

From source file:domain.Pdfmaker.java

public void makePdf() {
    Document doc = new Document();
    doc.setPageSize(PageSize.A4);//from w w w  .  j  ava 2s. c  o  m
    try {
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(test.getTitle() + ".pdf"));
        writer.setPdfVersion(PdfWriter.VERSION_1_7);
        doc.open();
        Font f = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.BOLD, new BaseColor(0, 0, 0));
        Paragraph title = new Paragraph("TEST TITLE", f);
        title.setAlignment(Element.ALIGN_CENTER);
        doc.addCreator("Arne De Bremme");
        //make table
        PdfPTable table = new PdfPTable(4);
        table.setTotalWidth(550f);
        table.setLockedWidth(true);
        table.setHeaderRows(1);

        Paragraph p = new Paragraph(test.getTitle());
        p.setAlignment(Element.ALIGN_CENTER);
        PdfPCell cell = new PdfPCell(p);
        cell.setGrayFill(0.7f);
        cell.setColspan(4);
        table.addCell(cell);
        table.addCell(test.getClassGroup().getGroupName());
        PdfPCell cell2 = new PdfPCell(new Paragraph(test.getDescription()));
        cell2.setColspan(2);
        cell2.setRowspan(2);
        table.addCell(cell2);
        PdfPCell cell3 = new PdfPCell(new Paragraph("DD " + test.getStartDate().getDay() + "/"
                + test.getStartDate().getMonth() + "/" + test.getStartDate().getYear()));
        cell3.setRowspan(2);
        table.addCell(cell3);
        table.addCell(new Paragraph("Test " + test.getTestId()));
        doc.add(table);
        doc.add(Chunk.NEWLINE);
        for (Exercise e : ex) {
            Paragraph par = new Paragraph();
            par.add("Vraag " + counter);
            par.add(Chunk.TABBING);
            par.add(Chunk.TABBING);
            par.add(Chunk.TABBING);
            par.add(Chunk.TABBING);
            par.add(e.getPunten() + "/");
            doc.add(par);
            doc.add(new Paragraph("Klimatogram " + e.getClimateChart().getLocation() + " " + e.getPunten()));
            Robot r = new Robot();
            Desktop.getDesktop().browse(new URI(
                    "http://climatechart.azurewebsites.net/ClimateChart/ShowExercises?selectedYear=1&continentId="
                            + e.getClimateChart().getCountry().getContinent().getId() + "&countryId="
                            + e.getClimateChart().getCountry().getContinent().getId() + "&climateId="
                            + e.getClimateChart().getId()));
            TimeUnit.SECONDS.sleep(6);
            BufferedImage bi = r.createScreenCapture(
                    new Rectangle(Toolkit.getDefaultToolkit().getScreenSize().width * 7 / 10,
                            Toolkit.getDefaultToolkit().getScreenSize().width * 8 / 14));
            File file = new File("screenCapture" + counter + ".jpg");
            ImageIO.write(bi, "jpg", file);
            Image img = Image.getInstance("screenCapture.jpg");
            img.scaleAbsolute(400, 300);
            doc.add(img);
            doc.add(Chunk.NEWLINE);
            doc.add(new Paragraph(e.getNaam()));
            doc.add(Chunk.NEXTPAGE);
            counter++;

        }

        doc.close();
        File filz = new File(test.getTitle() + ".pdf");
        Desktop.getDesktop().open(filz);
    } catch (Exception e) {

    }
}

From source file:net.sf.texprinter.generators.PDFGenerator.java

License:Open Source License

/**
 * Generates a PDF file from a Question object.
 * //from  w  ww.j  a va 2  s.  com
 * @param question The question.
 * @param filename The filename.
 */
public static void generate(Question question, String filename) {

    // wait window
    ProgressMessage pm = new ProgressMessage("TeXPrinter is printing your PDF file.");

    // start wait window
    //pm.start();

    // log message
    log.log(Level.INFO, "Starting PDF generation of {0}.", filename);

    // define a new PDF document
    Document document = null;

    // define a new PDF writer
    PdfWriter writer = null;

    // lets try
    try {

        // create a new PDF document
        document = new Document();

        // define a new PDF Writer
        writer = PdfWriter.getInstance(document, new FileOutputStream(filename));

        // set the PDF version
        writer.setPdfVersion(PdfWriter.VERSION_1_6);

        // open the document
        document.open();

        // set the title font
        Font titleFont = new Font(FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK);

        // set the chunk for the question title
        Chunk questionTitle = new Chunk(question.getQuestion().getTitle(), titleFont);

        // create a paragraph from that chunk
        Paragraph paragraphQuestionTitle = new Paragraph(questionTitle);

        // log message
        log.log(Level.INFO, "Adding the question title.");

        // add the question title to the document
        document.add(paragraphQuestionTitle);

        // set the asker font
        Font askerFont = new Font(FontFamily.HELVETICA, 10, Font.ITALIC, BaseColor.DARK_GRAY);

        // set the chunk for the asker
        Chunk questionAsker = new Chunk("Asked by " + question.getQuestion().getUser().getName() + " ("
                + question.getQuestion().getUser().getReputation() + ") on " + question.getQuestion().getDate()
                + " (" + String.valueOf(question.getQuestion().getVotes())
                + (question.getQuestion().getVotes() == 1 ? " vote" : " votes") + ")", askerFont);

        // create a paragraph from that chunk
        Paragraph paragraphQuestionAsker = new Paragraph(questionAsker);

        // log message
        log.log(Level.INFO, "Adding both asker and reputation.");

        // add the asker to the document
        document.add(paragraphQuestionAsker);

        // create a line separator
        LineSeparator line = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -5);

        // add the line to the document
        document.add(line);

        // add a new line
        document.add(Chunk.NEWLINE);

        // create a list of elements from the question objects
        List<Element> questionTextObjects = getPostText(question.getQuestion().getText());

        // log message
        log.log(Level.INFO, "Adding the question text.");

        // for each element
        for (Element questionTextObject : questionTextObjects) {

            // add it to the document
            document.add(questionTextObject);
        }

        // add a new line
        document.add(Chunk.NEWLINE);

        // create a new font for the comments title
        Font commentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK);

        // create a new chunk based on that font
        Chunk commentsTitle = new Chunk(
                "This question has " + question.getQuestion().getComments().size()
                        + ((question.getQuestion().getComments().size() == 1) ? " comment:" : " comments:"),
                commentsTitleFont);

        // create a paragraph from that chunk
        Paragraph paragraphCommentsTitle = new Paragraph(commentsTitle);

        // if there are comments to this question
        if (!question.getQuestion().getComments().isEmpty()) {

            // log message
            log.log(Level.INFO, "Adding the question comments.");

            // add that paragraph to the document
            document.add(paragraphCommentsTitle);

            // add a new line
            document.add(Chunk.NEWLINE);

            // get all the comments
            List<Comment> questionComments = question.getQuestion().getComments();

            // for each comment
            for (Comment questionComment : questionComments) {

                // get the elements of the comment text
                List<Element> questionCommentObjects = getPostText(questionComment.getText());

                // for each element
                for (Element questionCommentObject : questionCommentObjects) {

                    // add it to the document
                    document.add(questionCommentObject);
                }

                // create a new paragraph about the comment author
                Paragraph paragraphCommentAuthor = new Paragraph(questionComment.getAuthor() + " on "
                        + questionComment.getDate() + " (" + String.valueOf(questionComment.getVotes())
                        + (questionComment.getVotes() == 1 ? " vote" : " votes") + ")", askerFont);

                // set the alignment to the right
                paragraphCommentAuthor.setAlignment(Element.ALIGN_RIGHT);

                // add the paragraph to the document
                document.add(paragraphCommentAuthor);

                // add a new line
                document.add(Chunk.NEWLINE);
            }
        }

        // add a line separator
        document.add(line);

        // add two new lines
        document.add(Chunk.NEWLINE);
        document.add(Chunk.NEWLINE);

        // get the list of answers
        List<Post> answersList = question.getAnswers();

        // if there are no answers
        if (answersList.isEmpty()) {

            // log message
            log.log(Level.INFO, "This question has no answers.");

            // create a new chunk
            Chunk noAnswersTitle = new Chunk("Sorry, this question has no answers yet.", titleFont);

            // create a paragraph from that chunk
            Paragraph paragraphNoAnswersTitle = new Paragraph(noAnswersTitle);

            // add the paragraph to the document
            document.add(paragraphNoAnswersTitle);

        } else {

            // log message
            log.log(Level.INFO, "Adding answers.");

            // there are answers, so create a counter for answers
            int answerCount = 1;

            // for each answer
            for (Post answer : answersList) {

                // log message
                log.log(Level.INFO, "Adding answer {0}.", answerCount);

                // set the message text as empty
                String answerAccepted = "";

                // if the answer is accepted
                if (answer.isAccepted()) {

                    // add that to the message
                    answerAccepted = " - Marked as accepted.";
                }

                // create a new chunk
                Chunk answerTitle = new Chunk("Answer #" + answerCount, titleFont);

                // create a paragraph from that chunk
                Paragraph paragraphAnswerTitle = new Paragraph(answerTitle);

                // add the paragraph to the document
                document.add(paragraphAnswerTitle);

                // increase the counter
                answerCount++;

                // create a new chunk
                Chunk questionAnswerer = new Chunk("Answered by " + answer.getUser().getName() + " ("
                        + answer.getUser().getReputation() + ") on " + answer.getDate() + answerAccepted + " ("
                        + String.valueOf(answer.getVotes()) + (answer.getVotes() == 1 ? " vote" : " votes")
                        + ")", askerFont);

                // create a paragraph from that chunk
                Paragraph paragraphQuestionAnswerer = new Paragraph(questionAnswerer);

                // add that paragraph to the document
                document.add(paragraphQuestionAnswerer);

                // add a line separator
                document.add(line);

                // add a new line
                document.add(Chunk.NEWLINE);

                // create a list of elements from the answer text
                List<Element> answerTextObjects = getPostText(answer.getText());

                // for each element
                for (Element answerTextObject : answerTextObjects) {

                    // add it to the document
                    document.add(answerTextObject);
                }

                // add a new line
                document.add(Chunk.NEWLINE);

                // create a new font style
                Font answerCommentsTitleFont = new Font(FontFamily.HELVETICA, 12, Font.BOLD, BaseColor.BLACK);

                // create a new chunk
                Chunk answerCommentsTitle = new Chunk(
                        "This answer has " + answer.getComments().size()
                                + ((answer.getComments().size() == 1) ? " comment:" : " comments:"),
                        answerCommentsTitleFont);

                // create a paragraph from that chunk
                Paragraph paragraphAnswerCommentsTitle = new Paragraph(answerCommentsTitle);

                // if there are comments for that answer
                if (!answer.getComments().isEmpty()) {

                    // log message
                    log.log(Level.INFO, "Adding comments for answer {0}.", (answerCount - 1));

                    // add that paragraph to the document
                    document.add(paragraphAnswerCommentsTitle);

                    // add a new line
                    document.add(Chunk.NEWLINE);

                    // get all the comments
                    List<Comment> answerComments = answer.getComments();

                    // for each comment
                    for (Comment answerComment : answerComments) {

                        // create a list of elements from the comment text
                        List<Element> answerCommentObjects = getPostText(answerComment.getText());

                        // for each element
                        for (Element answerCommentObject : answerCommentObjects) {

                            // add it to the document
                            document.add(answerCommentObject);
                        }

                        // create a new paragraph for the comment author
                        Paragraph paragraphAnswerCommentAuthor = new Paragraph(
                                answerComment.getAuthor() + " on " + answerComment.getDate() + " ("
                                        + String.valueOf(answerComment.getVotes())
                                        + (answerComment.getVotes() == 1 ? " vote" : " votes") + ")",
                                askerFont);

                        // set the aligment to the right
                        paragraphAnswerCommentAuthor.setAlignment(Element.ALIGN_RIGHT);

                        // add the paragraph to the document
                        document.add(paragraphAnswerCommentAuthor);

                        // add a new line
                        document.add(Chunk.NEWLINE);
                    }
                }

                // add a line separator
                document.add(line);

                // add two new lines
                document.add(Chunk.NEWLINE);
                document.add(Chunk.NEWLINE);
            }
        }

        // log message
        log.log(Level.INFO, "PDF generation complete, closing {0}.", filename);

        // close the document
        document.close();

        // stop wait window
        pm.interrupt();

    } catch (IOException ioexception) {

        // stop wait window
        pm.interrupt();

        // log message
        log.log(Level.SEVERE, "An IO error occurred while trying to create the PDF file. MESSAGE: {0}",
                StringUtils.printStackTrace(ioexception));

        // critical error, exit
        Dialogs.showExceptionWindow();

    } catch (Exception exception) {

        // log message
        log.log(Level.SEVERE, "A generic error occurred while trying to create the PDF file. MESSAGE: {0}",
                StringUtils.printStackTrace(exception));

        // log message
        log.log(Level.INFO, "I will try to remove the remaining PDF file.");

        try {

            // log message
            log.log(Level.INFO, "Closing both document and writer.");

            // close the document
            document.close();

            // close the writer
            writer.close();

        } catch (Exception ex) {

            // log message
            log.log(Level.WARNING, "I could not close either document or writer. MESSAGE: {0}",
                    StringUtils.printStackTrace(ex));
        }

        try {

            // reference problematic file
            File target = new File(filename);

            // log message
            log.log(Level.INFO, "Opening problematic file {0}.", filename);

            // check if file exists
            if (target.exists()) {

                // log message
                log.log(Level.INFO, "File exists, trying to delete it.");

                // trying to remove it
                if (target.delete()) {

                    // log message
                    log.log(Level.INFO, "File {0} was successfully removed.", filename);

                } else {

                    // log message
                    log.log(Level.SEVERE, "File {0} could not be removed.", filename);

                }
            }
        } catch (SecurityException se) {

            // log message
            log.log(Level.SEVERE, "A security exception was raised. MESSAGE: {0}",
                    StringUtils.printStackTrace(se));

        }

        // stop wait window
        pm.interrupt();

        // critical error, exit
        Dialogs.showExceptionWindow();

    }
}

From source file:org.gephi.io.exporter.preview.PDFExporter.java

License:Open Source License

public boolean execute() {
    Progress.start(progress);//from  ww w. j  a v a  2  s . c o m

    PreviewController controller = Lookup.getDefault().lookup(PreviewController.class);
    controller.getModel(workspace).getProperties().putValue(PreviewProperty.VISIBILITY_RATIO, 1.0);
    controller.refreshPreview(workspace);
    PreviewProperties props = controller.getModel(workspace).getProperties();

    Rectangle size = new Rectangle(pageSize);
    if (landscape) {
        size = new Rectangle(pageSize.rotate());
    }
    Color col = props.getColorValue(PreviewProperty.BACKGROUND_COLOR);
    size.setBackgroundColor(new BaseColor(col.getRed(), col.getGreen(), col.getBlue()));

    Document document = new Document(size);
    PdfWriter pdfWriter = null;
    try {
        pdfWriter = PdfWriter.getInstance(document, stream);
        pdfWriter.setPdfVersion(PdfWriter.PDF_VERSION_1_5);
        pdfWriter.setFullCompression();

    } catch (DocumentException ex) {
        Exceptions.printStackTrace(ex);
    }
    document.open();
    PdfContentByte cb = pdfWriter.getDirectContent();
    cb.saveState();

    props.putValue(PDFTarget.LANDSCAPE, landscape);
    props.putValue(PDFTarget.PAGESIZE, size);
    props.putValue(PDFTarget.MARGIN_TOP, new Float((float) marginTop));
    props.putValue(PDFTarget.MARGIN_LEFT, new Float((float) marginLeft));
    props.putValue(PDFTarget.MARGIN_BOTTOM, new Float((float) marginBottom));
    props.putValue(PDFTarget.MARGIN_RIGHT, new Float((float) marginRight));
    props.putValue(PDFTarget.PDF_CONTENT_BYTE, cb);
    target = (PDFTarget) controller.getRenderTarget(RenderTarget.PDF_TARGET, workspace);
    if (target instanceof LongTask) {
        ((LongTask) target).setProgressTicket(progress);
    }

    try {
        controller.render(target, workspace);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    cb.restoreState();
    document.close();

    Progress.finish(progress);

    props.putValue(PDFTarget.PDF_CONTENT_BYTE, null);
    props.putValue(PDFTarget.PAGESIZE, null);

    return !cancel;
}

From source file:pdf.PdfBuilder.java

/**
 * Creates an accessible PDF with images and text.
 * @param dest  the path to the resulting PDF
 * @throws IOException//from   w  w  w . ja v  a 2  s. c  o  m
 * @throws DocumentException
 */
public String createPdf(Invoice invoice) throws IOException, DocumentException {
    DEST = "C://temp/";
    SimpleDateFormat sdf = new SimpleDateFormat("MM");
    DEST += invoice.getCar().getId() + "month"
            + sdf.format(invoice.getSeriesOfLocationsOnRoad().get(0).getLocations().get(0).getDate()) + ".pdf";

    File file = new File(DEST);
    file.getParentFile().mkdirs();

    Document document = new Document(PageSize.A4.rotate());
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
    writer.setPdfVersion(PdfWriter.VERSION_1_7);
    //TAGGED PDF
    //Make document tagged
    writer.setTagged();
    //===============
    //PDF/UA
    //Set document metadata
    writer.setViewerPreferences(PdfWriter.DisplayDocTitle);
    document.addLanguage("en-US");
    document.addTitle("Factuur voor auto " + invoice.getCar().getLicensePlate());
    writer.createXmpMetadata();
    //=====================
    document.open();

    Font font = FontFactory.getFont(FONT, BaseFont.WINANSI, BaseFont.EMBEDDED, 20);

    double amountPaidForDistance = invoice.getTotalAmount();
    double amountPaidForCordons = 0;

    for (Cordon c : invoice.getCordonOccurrences()) {
        amountPaidForDistance -= c.getAmount();
        amountPaidForCordons += c.getAmount();
    }

    Paragraph p = new Paragraph("\n", font);
    p.add(new Chunk("Aantal gereden kilometers:"));
    p.add(new Chunk("\n"));
    p.add(new Chunk(String.valueOf(invoice.getTotalDistance()) + " kilometer"));
    p.add(new Chunk("\n"));
    p.add(new Chunk("Met een gemiddeld tarief van " + (amountPaidForDistance / invoice.getTotalDistance() * 100)
            + " eurocent per kilometer"));
    p.add(new Chunk("\n"));
    p.add(new Chunk("Bedrag dat betaald dient te worden over de kilometers: "));
    p.add(new Chunk("\n"));
    p.add(new Chunk(amountPaidForDistance + " euro"));
    document.add(p);

    p = new Paragraph("\n\n", font);
    p.add(new Chunk(invoice.cordonOccurrencesString()));
    p.add(new Chunk("\n"));
    p.add(new Chunk("Bedrag dat betaald dient te worden over de cordons: "));
    p.add(new Chunk("\n"));
    p.add(new Chunk(amountPaidForCordons + " euro"));
    document.add(p);

    p = new Paragraph("\n\n", font);
    p.add(new Chunk("Totaal bedrag dat betaald dient te worden: "));
    p.add(new Chunk("\n"));
    p.add(new Chunk(String.valueOf(invoice.getTotalAmount()) + " euro"));
    document.add(p);
    document.close();

    return DEST;
}

From source file:pdfcreator.PDFCreator.java

License:Open Source License

@SuppressWarnings("static-access")
protected void createPdf(String filename, String[] images) throws Exception {
    Document doc = new Document();
    PdfWriter writer;

    if (pdfxConformance.equals("PDFA1A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1A);
    } else if (pdfxConformance.equals("PDFA1B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_1B);
    } else if (pdfxConformance.equals("PDFA2A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_2A);
    } else if (pdfxConformance.equals("PDFA2B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_2B);
    } else if (pdfxConformance.equals("PDFA3A")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_3A);
    } else if (pdfxConformance.equals("PDFA3B")) {
        writer = PdfAWriter.getInstance(doc, new FileOutputStream(filename), PdfAConformanceLevel.PDF_A_3B);
    } else {//from  w  w w . ja v a2 s.co m
        writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
    }

    if (pdfVersion.equals("1.4")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_4);
    } else if (pdfVersion.equals("1.5")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_5);
    } else if (pdfVersion.equals("1.6")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_6);
    } else if (pdfVersion.equals("1.7")) {
        writer.setPdfVersion(PdfWriter.VERSION_1_7);
    } else {
        writer.setPdfVersion(PdfWriter.VERSION_1_4);
    }

    verbose(filename + ": open");

    doc.addCreationDate();
    doc.addCreator(creator);

    if (title != null) {
        doc.addTitle(title);
    }

    for (int i = 0; i < images.length; i++) {
        verbose(" +" + images[i]);

        Image img = Image.getInstance(images[i]);

        doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
        doc.setMargins(0, 0, 0, 0);

        if (doc.isOpen()) {
            doc.newPage();
        } else {
            doc.open();
        }

        doc.add(img);

        doc.newPage();
    }

    ICC_Profile icc = getImageColorProfile(images[0]);

    if (icc == null) {
        System.err.println("warning: no color profile available in " + images[0] + " using " + profileName);
        icc = getDefaultColorProfile();
    }

    writer.setOutputIntents("Custom", "", null, null, icc);

    writer.createXmpMetadata();

    doc.close();

    verbose(filename + ": close");
}

From source file:ptolemy.vergil.basic.export.itextpdf.ExportPDFAction.java

License:Open Source License

/** Export PDF to a file.
 *  This uses the iText library at http://itextpdf.com/.
 *
 *  <p>If {@link ptolemy.gui.PtGUIUtilities#useFileDialog()} returns true
 *  then a java.awt.FileDialog is used, otherwise a javax.swing.JFileChooser
 *  is used.</p>//www  .  ja  va 2  s. c  o  m
 */
private void _exportPDF() {
    Dimension size = _frame.getContentSize();
    Rectangle pageSize = null;
    try {
        pageSize = new Rectangle(size.width, size.height);
    } catch (Throwable ex) {
        // This exception will occur if the iText library is not installed.
        MessageHandler.error("iText library is not installed. See http://itextpdf.com/."
                + "  You must have iText.jar in your classpath.  Sometimes, "
                + "iText.jar may be found in $PTII/vendors/itext/iText.jar.", ex);
        return;
    }
    Document document = new Document(pageSize);
    JFileChooserBugFix jFileChooserBugFix = new JFileChooserBugFix();
    Color background = null;
    PtFileChooser ptFileChooser = null;
    try {
        background = jFileChooserBugFix.saveBackground();

        ptFileChooser = new PtFileChooser(_frame, "Specify a pdf file to be written.",
                JFileChooser.SAVE_DIALOG);

        LinkedList extensions = new LinkedList();
        extensions.add("pdf");
        ptFileChooser.addChoosableFileFilter(new ExtensionFilenameFilter(extensions));

        BasicGraphFrame basicGraphFrame = null;
        if (_frame instanceof BasicGraphFrame) {
            basicGraphFrame = (BasicGraphFrame) _frame;
            ptFileChooser.setCurrentDirectory(basicGraphFrame.getLastDirectory());
            ptFileChooser.setSelectedFile(new File(basicGraphFrame.getModel().getName() + ".pdf"));
        }
        int returnVal = ptFileChooser.showDialog(_frame, "Export PDF");

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if (basicGraphFrame != null) {
                basicGraphFrame.setLastDirectory(ptFileChooser.getCurrentDirectory());
            }
            File pdfFile = ptFileChooser.getSelectedFile().getCanonicalFile();

            if (pdfFile.getName().indexOf(".") == -1) {
                // If the user has not given the file an extension, add it
                pdfFile = new File(pdfFile.getAbsolutePath() + ".pdf");
            }

            // The Mac OS X FileDialog will ask if we want to save before this point.
            if (pdfFile.exists() && !PtGUIUtilities.useFileDialog()) {
                if (!MessageHandler.yesNoQuestion("Overwrite " + pdfFile.getName() + "?")) {
                    return;
                }
            }

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            // To ensure Latex compatibility, use earlier PDF version.
            writer.setPdfVersion(PdfWriter.VERSION_1_3);
            document.open();
            PdfContentByte contentByte = writer.getDirectContent();

            PdfTemplate template = contentByte.createTemplate(size.width, size.height);
            Graphics2D graphics = template.createGraphics(size.width, size.height);
            template.setWidth(size.width);
            template.setHeight(size.height);

            Paper paper = new Paper();
            paper.setSize(size.width, size.height);
            paper.setImageableArea(0.0, 0.0, size.width, size.height);
            PageFormat format = new PageFormat();
            format.setPaper(paper);
            ((Printable) _frame).print(graphics, format, 0);
            graphics.dispose();
            contentByte.addTemplate(template, 0, 0);

            // Open the PDF file.
            // FIXME: _read is protected in BasicGraphFrame
            //_read(pdfFile.toURI().toURL());
            // Open the image pdfFile.
            if (basicGraphFrame == null) {
                MessageHandler.message("PDF file exported to " + pdfFile.getName());
                /* Remove the following. The extra click is annoying...
                } else {
                if (MessageHandler.yesNoQuestion("Open \""
                        + pdfFile.getCanonicalPath() + "\" in a browser?")) {
                    Configuration configuration = basicGraphFrame
                            .getConfiguration();
                    try {
                        URL imageURL = new URL(pdfFile.toURI().toURL()
                                .toString()
                                + "#in_browser");
                        configuration.openModel(imageURL, imageURL,
                                imageURL.toExternalForm(),
                                BrowserEffigy.staticFactory);
                    } catch (Throwable throwable) {
                        MessageHandler.error(
                                "Failed to open \"" + pdfFile.getName()
                                        + "\".", throwable);
                    }
                }
                 */
            }
        }
    } catch (Exception e) {
        MessageHandler.error("Export to PDF failed", e);
    } finally {
        try {
            document.close();
        } finally {
            jFileChooserBugFix.restoreBackground(background);
        }
    }
}