Example usage for com.lowagie.text.pdf PdfReader PdfReader

List of usage examples for com.lowagie.text.pdf PdfReader PdfReader

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfReader PdfReader.

Prototype

public PdfReader(PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

From source file:questions.stamppages.PageXofYRightAligned.java

public static void main(String[] args) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//from   ww  w  .  ja v a  2 s.  c o  m
        Document document = new Document();
        PdfWriter.getInstance(document, baos);
        document.open();
        BufferedReader reader = new BufferedReader(new FileReader(RESOURCE));
        String line;
        Paragraph p;
        while ((line = reader.readLine()) != null) {
            p = new Paragraph(line);
            p.setAlignment(Element.ALIGN_JUSTIFIED);
            document.add(p);
            document.newPage();
        }
        reader.close();
        document.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

    try {
        PdfReader reader = new PdfReader(baos.toByteArray());
        int n = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        PdfContentByte page;
        Rectangle rect;
        BaseFont bf = BaseFont.createFont();
        for (int i = 1; i < n + 1; i++) {
            page = stamper.getOverContent(i);
            rect = reader.getPageSizeWithRotation(i);
            page.beginText();
            page.setFontAndSize(bf, 12);
            page.showTextAligned(Element.ALIGN_RIGHT, "page " + i + " of " + n, rect.getRight(36),
                    rect.getTop(32), 0);
            page.endText();
        }
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:questions.stamppages.RemoveAttachmentAnnotations.java

public static void main(String[] args) throws IOException, DocumentException {
    createPdfWithAttachments();/*  w ww.  j  a  va  2  s  .  c o  m*/
    PdfReader reader = new PdfReader(RESOURCE);
    PdfDictionary page;
    PdfDictionary annotation;
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        page = reader.getPageN(i);
        PdfArray annots = page.getAsArray(PdfName.ANNOTS);
        if (annots != null) {
            for (int j = annots.size() - 1; j >= 0; j--) {
                annotation = annots.getAsDict(j);
                if (PdfName.FILEATTACHMENT.equals(annotation.get(PdfName.SUBTYPE))) {
                    annots.remove(j);
                }
            }
        }
    }
    reader.removeUnusedObjects();
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
    stamper.close();
}

From source file:questions.stamppages.StampAndAddColumns.java

public static void main(String[] args) {
    try {/*from  ww w  .  j  a v a  2 s .c o m*/
        PdfReader reader = new PdfReader(RESOURCE);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        AcroFields form = stamper.getAcroFields();
        form.setField("Who", "world");
        ColumnText ct = new ColumnText(stamper.getOverContent(1));
        String line;
        Phrase p;
        BufferedReader br = new BufferedReader(new FileReader(TXT));
        while ((line = br.readLine()) != null) {
            p = new Phrase(line + "\n");
            ct.addText(p);
        }
        int status = ColumnText.START_COLUMN;
        ct.setSimpleColumn(100, 700, 495, 100);
        status = ct.go();
        int pageCt = 1;
        while (ColumnText.hasMoreText(status)) {
            stamper.insertPage(++pageCt, reader.getPageSize(1));
            ct.setYLine(700);
            ct.setCanvas(stamper.getOverContent(pageCt));
            status = ct.go();
        }
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:s2s.luna.reports.Stampa_documento.java

License:GNU General Public License

@SuppressWarnings("CallToThreadDumpStack")
private boolean addPDF(String titolo, byte[] fileContent, Document document, PdfWriter writer) {
    try {//from  w w w .  j  a v  a 2s . co m
        // Inizializzo il contenitore del pdf da importare.
        PdfContentByte cb = writer.getDirectContent();

        // Inizializzo la variabile dove appogger (una alla volta)
        // le pagine del pdf da importare.
        PdfImportedPage page;

        // Apro in lettura il pdf da importare.
        PdfReader pdfReader = new PdfReader(fileContent);

        // Ne determino il numero di pagine totali.
        int pdfPageNumber = pdfReader.getNumberOfPages();

        // Inzializzo il contatore delle pagine.
        int pageOfCurrentReaderPDF = 1;

        // Per ogni pagina...
        while (pageOfCurrentReaderPDF <= pdfPageNumber) {
            // Creo una nuova pagina vuota sul pdf di destinazione.
            document.newPage();
            // Estraggo la pagina dal pdf da importare.
            page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
            // Coverto la pagina in un immagine.
            Image pageImg = Image.getInstance(page);
            // Aggiungo la pagina estratta al pdf di destinazione, ruotandola se necessario.
            PdfPTable table = new PdfPTable(1);
            PdfPCell defaultCell = table.getDefaultCell();
            defaultCell.setRotation(-pdfReader.getPageRotation(pageOfCurrentReaderPDF));
            defaultCell.setBorder(Rectangle.NO_BORDER);
            table.addCell(pageImg);
            document.add(table);
            // Incremento il contatore delle pagine
            pageOfCurrentReaderPDF++;
        }
        return true;
    } catch (Exception ex) {
        // Eccezione silenziosa.
        // Gestisce il caso in cui si verifica un errore non previsto
        ex.printStackTrace();
        return false;
    }
}

From source file:si.vsrs.cif.svev.example.utils.PDFSignature.java

License:EUPL

public File signPDF(File document, InputStream keystore, String password, String keyPassord,
        String keystoreType, String alias, boolean bshowVisualization) {
    if (document == null || !document.exists()) {
        throw new RuntimeException("Error reading pdf");
    }/*from   w ww . j a v a 2  s . com*/

    String name = document.getName();
    String substring = name.substring(0, name.lastIndexOf("."));

    File outputDocument = new File(document.getParent(), substring + "_signed.pdf");

    try (FileInputStream fis = new FileInputStream(document);
            FileOutputStream fout = new FileOutputStream(outputDocument)) {

        KeyStore ks = KeyStore.getInstance(keystoreType);
        ks.load(keystore, password.toCharArray());
        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassord.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);
        X509Certificate xcert = (X509Certificate) chain[0];
        PdfReader reader = new PdfReader(fis);

        char tmpPdfVersion = '\0'; // default version - the same as input
        final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, true);
        final PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        sap.setReason("Testni podpis");
        sap.setLocation("Maribor");
        sap.setContact(xcert.getSubjectDN().getName());

        //            sap.setLayer2Text("");
        //          sap.setLayer4Text("");
        sap.setAcro6Layers(true); // --:> 

        Rectangle rc = reader.getPageSize(1);
        if (bshowVisualization) {
            sap.setVisibleSignature(new Rectangle(5, rc.getHeight() - 40, 240, rc.getHeight() - 5), 1, null);
        }

        final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));

        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate()));
        sap.setCryptoDictionary(dic);
        final int contentEstimated = 15000;
        final HashMap<PdfName, Integer> exc = new HashMap<>();
        exc.put(PdfName.CONTENTS, contentEstimated * 2 + 2);
        sap.preClose(exc);

        PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA-256", null, false);
        InputStream data = sap.getRangeStream();
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte buf[] = new byte[8192];
        int n;
        while ((n = data.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        Calendar cal = Calendar.getInstance();

        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null);
        sgn.update(sh, 0, sh.length);

        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, null, null);

        byte[] paddedSig = new byte[contentEstimated];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);

        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));

        sap.close(dic2);
    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException
            | UnrecoverableKeyException | DocumentException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }

    return outputDocument;
}

From source file:sos.util.security.SOSPDFSignatur.java

License:Apache License

/**
 * PDF Signatur erzeugen/*from   www.j av  a 2  s.com*/
 * 
 * @param privateKey      Private Key
 * @param chain            Certificate Chain
 * @param originalPdfName   Original PDF Datei zur Signierung
 * @param outputPdfName      Output (signierte) PDF Datei
 * @throws Exception
 */
public static void createSignatur(PrivateKey privateKey, Certificate[] chain, String originalPdfName,
        String outputPdfName) throws Exception {

    PdfReader reader = new PdfReader(originalPdfName);
    FileOutputStream fout = new FileOutputStream(outputPdfName);

    //createSignature(PdfReader reader, OutputStream os, char pdfVersion)
    //pdfVersion - the new pdf version or '\0' to keep the same version as
    // the original document

    PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    //setCrypto(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, PdfName filter) 
    // CRL - certificate revocation lists (CRLs) that have different formats but important common uses.
    //       For example, all CRLs share the functionality of listing revoked certificates, and can be queried on whether or not they list a given certificate.
    // PdfName
    // SELF_SIGNED       -    The self signed filter
    // VERISIGN_SIGNED  -    The VeriSign filter
    // WINCER_SIGNED    -    The Windows Certificate Security
    sap.setCrypto(privateKey, chain, null, PdfSignatureAppearance.SELF_SIGNED);
    //sap.setCrypto(privateKey, chain, null,PdfSignatureAppearance.WINCER_SIGNED);

    sap.setReason(SOSPDFSignatur.reason);
    sap.setContact(SOSPDFSignatur.contact);
    sap.setLocation(SOSPDFSignatur.location);

    //GregorianCalendar cal = new GregorianCalendar();
    //sap.setSignDate(cal);

    //             comment next line to have an invisible signature
    //setVisibleSignature(Rectangle pageRect, int page, String fieldName)

    //sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
    //sap.setVisibleSignature(new Rectangle(100,100,200, 200), 1, null);

    if (SOSPDFSignatur.visible) {// todo
        //sap.setVisibleSignature(new Rectangle(200, 200, 400, 400), 1, null);
    }

    stp.close();

}

From source file:ud.ing.modi.controlador.ptorecarga.GeneracionFactura.java

public void generacionFacturaPDF() {
    try {/*from  ww w  .  ja  v a2  s .  co m*/
        System.out.println("Generaa");
        cargarDatosFactura();

        if (this.factura != null) {

            PdfReader reader = new PdfReader(
                    "C:\\Users\\Administrador\\Dropbox\\Tesis\\Monedero Digital\\Factura_PtoRecarga.pdf");
            String nombreFact = "D:\\REPOSITORIO TESIS2\\REPO\\MONEDERO_DIGITAL_APP\\MONEDERO_DIGITAL_APP_WEB\\src\\main\\webapp\\docs\\FACTURA_"
                    + traerUsu() + ".pdf";
            PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(nombreFact));
            AcroFields formulario = stamp.getAcroFields();

            formulario.setField("NUM_FACTURA", Integer.toString(this.factura.getCodFactura()));

            int mes = this.factura.getFechaCorte().getMonth() + 1;
            int anio = this.factura.getFechaCorte().getYear() + 1900;
            String fechaC = this.factura.getFechaCorte().getDate() + "-" + mes + "-" + anio;
            formulario.setField("FECHA_CORTE", fechaC);
            mes = this.factura.getFechaVencimiento().getMonth() + 1;
            anio = this.factura.getFechaVencimiento().getYear() + 1900;
            String fechaL = this.factura.getFechaVencimiento().getDate() + "-" + mes + "-" + anio;
            formulario.setField("FECHA_LIMITE", fechaL);
            formulario.setField("VALOR_PAGO", "$ " + Double.toString(this.factura.getValorTotalPago()));
            formulario.setField("COD_CLIENTE", Integer.toString(this.factura.getPuntoRecarga().getIdCliente()));
            formulario.setField("NOMBRE_CLIENTE", this.factura.getPuntoRecarga().getRazonSocial());
            formulario.setField("NUM_RECARGAS", Integer.toString(this.factura.getNumTotalRecargas()));
            formulario.setField("VALOR_RECARGAS", "$ " + Double.toString(this.factura.getValorTotalRecargas()));
            formulario.setField("VALOR_COMISION",
                    "$ " + Double.toString(this.factura.getValorCalculoComision()));

            stamp.setFormFlattening(true);
            stamp.close();

        }

    } catch (IOException ex) {
        Logger.getLogger(GeneracionFactura.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(GeneracionFactura.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:us.mn.state.health.lims.reports.action.implementation.CollectionReport.java

License:Mozilla Public License

protected byte[] merge(List<byte[]> byteList) throws DocumentException {
    byte[] outputBytes;
    OutputStream outputStream = new ByteArrayOutputStream();

    try {//from w  w  w  .j a v  a  2  s  .c o  m

        PdfCopyFields pcf = new PdfCopyFields(outputStream);
        for (byte[] bytes : byteList) {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            PdfReader pdfReader = new PdfReader(inputStream);

            // place holder in case we do have to rotate
            // if (false) {
            // int n = pdfReader.getNumberOfPages();
            // int rot;
            // PdfDictionary pageDict;
            // for (int i = 1; i <= n; i++) {
            // rot = pdfReader.getPageRotation(i);
            // pageDict = pdfReader.getPageN(i);
            // pageDict.put(PdfName.ROTATE, new PdfNumber(rot + 90));
            // }
            // }
            pcf.addDocument(pdfReader);
        }

        if (!byteList.isEmpty()) {
            pcf.close();
        }

        outputBytes = ((ByteArrayOutputStream) outputStream).toByteArray();

        return outputBytes;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } finally {
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    return null;
}

From source file:util.MyPDFFiles.java

public static void concatenar2PDF(String file1, String file2, String fileSale) throws Exception {

    System.out.println("Concatenate Two PDF");
    PdfReader reader1 = new PdfReader(file1);
    PdfReader reader2 = new PdfReader(file2);
    PdfCopyFields copy = new PdfCopyFields(new FileOutputStream(fileSale));
    copy.addDocument(reader1);// ww  w  . j  av  a 2 s . co  m
    copy.addDocument(reader2);
    copy.close();

}

From source file:util.PdfUtil.java

License:Open Source License

public String processText(String pdfFile) throws RedbasinException {
    try {//from   www . j  a va 2s  .  c om
        PdfReader reader = new PdfReader(pdfFile);
        return processText(reader);
    } catch (Exception e) {
        throw new RedbasinException("Some PdfReader error occured", e);
    }
}