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

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

Introduction

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

Prototype

char VERSION_1_7

To view the source code for com.itextpdf.text.pdf PdfWriter VERSION_1_7.

Click Source Link

Document

possible PDF version (header)

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  va  2s. c o 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:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;/* w w  w .  java  2s  . c o m*/

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:domain.Pdfmaker.java

public void makePdf() {
    Document doc = new Document();
    doc.setPageSize(PageSize.A4);/*w  ww  .  jav a 2s.co  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:org.h819.commons.file.MyPDFUtils.java

/**
 * ? pdf ??//from   w  ww .ja va  2 s.  co  m
 *
 * @param srcPdfFile  the original PDF
 * @param descPdfFile the resulting PDF
 * @throws java.io.IOException
 * @throws DocumentException
 */
public static void compressPdf(File srcPdfFile, File descPdfFile) throws IOException, DocumentException {

    if (srcPdfFile == null || !srcPdfFile.exists())
        throw new IOException("src pdf file '" + srcPdfFile + "' does not exsit.");

    PdfReader reader = getPdfReader(srcPdfFile);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(descPdfFile.getAbsoluteFile()),
            PdfWriter.VERSION_1_7);

    stamper.getWriter().setCompressionLevel(9);
    int total = reader.getNumberOfPages() + 1;
    for (int i = 1; i < total; i++) {
        reader.setPageContent(i, reader.getPageContent(i));
    }
    stamper.setFullCompression();
    stamper.close();
    reader.close();
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ?//from  w  ww . j a  va  2 s. c  o  m
 *
 * @param srcPdf
 * @param destPdf
 * @return
 * @throws IOException
 * @throws DocumentException
 */

public static PdfStamper getPdfStamper(File srcPdf, File destPdf) throws IOException, DocumentException {
    return new PdfStamper(getPdfReader(srcPdf), new FileOutputStream(destPdf), PdfWriter.VERSION_1_7);
}

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 ww w. j a  v  a2 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;// w w  w  .  j  a va 2 s .  co  m

    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 {
        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");
}