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

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

Introduction

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

Prototype

public PdfReader(final PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

From source file:jp.nichicom.ndk.affair.nu.nu001.NU001.java

License:Open Source License

/**
 * ???//from  w ww  .  j  av a 2s  .co m
 * @param e 
 * @throws Exception ?
 */
protected void compareActionPerformed(ActionEvent e) throws Exception {
    // 

    if (!new File(getPdf1().getText()).exists()) {
        ACMessageBox.showExclamation("PDF1?????");
        return;
    }
    if (!new File(getPdf2().getText()).exists()) {
        ACMessageBox.showExclamation("PDF2?????");
        return;
    }

    final PdfReader p1 = new PdfReader(getPdf1().getText());
    final PdfReader p2 = new PdfReader(getPdf2().getText());
    final int pages1 = p1.getNumberOfPages();
    final int pages2 = p2.getNumberOfPages();

    if (pages1 != pages2) {
        if (pages1 > pages2) {
            ACMessageBox.showExclamation("PDF1PDF2??????");
            return;
        }
        if (ACMessageBox.showOkCancel("PDF?????" + ACConstants.LINE_SEPARATOR
                + "PDF1??????PDF2?????????") != ACMessageBox.RESULT_OK) {
            return;
        }
    }

    new Runnable() {
        private boolean firstLock;

        public void run() {
            final int stopKeyCode = KeyEvent.VK_CAPS_LOCK;
            firstLock = Toolkit.getDefaultToolkit().getLockingKeyState(stopKeyCode);

            LinkedList<Integer> pages = new LinkedList<Integer>();
            for (int i = 1; i <= pages2; i++) {
                pages.add(new Integer(i));
            }

            errorCount = 0;
            pageOfProcessed = 0;
            pageOfCount = pages1;
            StringBuilder sb = new StringBuilder();

            for (int i = 1; i <= pages1; i++) {
                try {
                    boolean match = false;
                    byte[] b1 = p1.getPageContent(i);
                    Iterator<Integer> it = pages.iterator();
                    while (it.hasNext()) {
                        int page = ((Integer) it.next()).intValue();
                        byte[] b2 = p2.getPageContent(page);
                        if (Arrays.equals(b1, b2)) {
                            sb.append("PDF1(" + i + ") = PDF2(" + page + ")" + ACConstants.LINE_SEPARATOR);
                            match = true;
                            it.remove();
                            break;
                        }
                    }
                    if (!match) {
                        sb.append("PDF1(" + i + ") ???" + ACConstants.LINE_SEPARATOR);
                        errorCount++;
                    }
                } catch (Exception ex) {
                    sb.append("PDF1(" + i + ") ??" + ACConstants.LINE_SEPARATOR);
                    errorCount++;
                }

                setProgress(sb);
                pageOfProcessed = i;

                if (Toolkit.getDefaultToolkit().getLockingKeyState(stopKeyCode) != firstLock) {
                    getResult().setText(
                            "?(" + pageOfProcessed + " / " + pageOfCount + ") / ?:"
                                    + errorCount + " " + ACConstants.LINE_SEPARATOR + sb.toString());
                    return;
                }

            }

            getResult().setText("(" + pageOfProcessed + " / " + pageOfCount + ") / ?:"
                    + errorCount + " " + ACConstants.LINE_SEPARATOR + sb.toString());

        }

    }.run();

}

From source file:jp.opencollector.application.jpkipdf.JPKIPdfSigner.java

License:Open Source License

public static void main(String[] args) throws Exception {
    JPKIWrapper jpki = new JPKIWrapper();
    PdfReader reader = new PdfReader(args[0]);
    FileOutputStream fo = new FileOutputStream(args[1]);
    JPKIPdfStamper stamper = JPKIPdfStamper.createSignature(reader, fo,
            ResourceBundle.getBundle(JPKIPdfSigner.class.getPackage().getName() + ".messages"), '\0');
    JPKIPdfSignatureAppearance sa = stamper.getSignatureAppearance();
    sa.setCrypto(jpki, JPKIPdfSignatureAppearance.WINCER_SIGNED);
    stamper.close();//from ww w  . j a v  a  2  s  . com
}

From source file:jp.opencollector.application.jpkipdf.JPKIPdfSignerSWTGUI.java

License:Open Source License

/**
 * Create contents of the window./*from  ww w . j a v a  2  s  .c  om*/
 */
protected void createContents() {
    shlJpkiPdfSigner = new Shell();
    shlJpkiPdfSigner.setSize(456, 279);
    shlJpkiPdfSigner.setText(BUNDLE.getString("JPKIPdfSignerGUI.shlJpkiPdfSigner.text"));
    shlJpkiPdfSigner.setLayout(new FillLayout(SWT.HORIZONTAL));

    Composite composite_2 = new Composite(shlJpkiPdfSigner, SWT.NONE);
    composite_2.setLayout(new FormLayout());

    Label lblInputFile = new Label(composite_2, SWT.NONE);
    FormData fd_lblInputFile = new FormData();
    fd_lblInputFile.left = new FormAttachment(0, 10);
    fd_lblInputFile.top = new FormAttachment(0, 13);
    lblInputFile.setLayoutData(fd_lblInputFile);
    lblInputFile.setText(BUNDLE.getString("JPKIPdfSignerGUI.lblInputFile.text"));

    Label lblOutputFile = new Label(composite_2, SWT.NONE);
    FormData fd_lblOutputFile = new FormData();
    fd_lblOutputFile.top = new FormAttachment(lblInputFile, 18);
    fd_lblOutputFile.left = new FormAttachment(0, 10);
    lblOutputFile.setLayoutData(fd_lblOutputFile);
    lblOutputFile.setText(BUNDLE.getString("JPKIPdfSignerGUI.lblOutputFile.text"));

    Button btnInputFile = new Button(composite_2, SWT.NONE);
    btnInputFile.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent ev) {
            FileDialog dialog = new FileDialog(shlJpkiPdfSigner, SWT.OPEN);
            dialog.setFilterExtensions(EXTENSIONS);
            dialog.open();
            final String fileName = dialog.getFileName();
            if (fileName != null && fileName.length() > 0) {
                final String parentDirectory = dialog.getFilterPath();
                textInputFile.setText(parentDirectory + java.io.File.separatorChar + fileName);
                if (textOutputFile.getText().length() == 0) {
                    final int i = fileName.lastIndexOf('.');
                    final String outputFileName = i >= 0
                            ? fileName.substring(0, i) + ".signed" + fileName.substring(i)
                            : fileName + ".signed";
                    textOutputFile.setText(parentDirectory + java.io.File.separatorChar + outputFileName);
                }
            }
        }
    });
    FormData fd_btnInputFile = new FormData();
    fd_btnInputFile.top = new FormAttachment(0, 5);
    fd_btnInputFile.left = new FormAttachment(100, -49);
    fd_btnInputFile.right = new FormAttachment(100, -10);
    btnInputFile.setLayoutData(fd_btnInputFile);
    btnInputFile.setText("...");

    Button btnOutputFile = new Button(composite_2, SWT.NONE);
    btnOutputFile.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            FileDialog dialog = new FileDialog(shlJpkiPdfSigner, SWT.OPEN);
            dialog.open();
            final String fileName = dialog.getFileName();
            if (fileName != null && fileName.length() > 0) {
                textOutputFile.setText(dialog.getFilterPath() + java.io.File.separatorChar + fileName);
            }
        }
    });
    FormData fd_btnOutputFile = new FormData();
    fd_btnOutputFile.top = new FormAttachment(btnInputFile, 2);
    fd_btnOutputFile.left = new FormAttachment(100, -49);
    fd_btnOutputFile.right = new FormAttachment(100, -10);
    btnOutputFile.setLayoutData(fd_btnOutputFile);
    btnOutputFile.setText("...");

    textInputFile = new Text(composite_2, SWT.BORDER);
    FormData fd_textInputFile = new FormData();
    fd_textInputFile.left = new FormAttachment(0, 107);
    fd_textInputFile.right = new FormAttachment(btnInputFile, -2);
    fd_textInputFile.top = new FormAttachment(0, 10);
    textInputFile.setLayoutData(fd_textInputFile);

    textOutputFile = new Text(composite_2, SWT.BORDER);
    fd_lblOutputFile.right = new FormAttachment(100, -355);
    FormData fd_textOutputFile = new FormData();
    fd_textOutputFile.left = new FormAttachment(0, 107);
    fd_textOutputFile.right = new FormAttachment(btnOutputFile);
    fd_textOutputFile.top = new FormAttachment(0, 42);
    textOutputFile.setLayoutData(fd_textOutputFile);

    SashForm sashForm = new SashForm(composite_2, SWT.NONE);
    FormData fd_sashForm = new FormData();
    fd_sashForm.bottom = new FormAttachment(100, -10);
    fd_sashForm.right = new FormAttachment(100, -10);
    fd_sashForm.left = new FormAttachment(0, 10, 10);
    fd_sashForm.height = 30;
    sashForm.setLayoutData(fd_sashForm);

    new Composite(sashForm, SWT.NONE);

    Composite composite = new Composite(sashForm, SWT.NONE);
    composite.setLayout(new FillLayout(SWT.HORIZONTAL));

    Button btnSignIt = new Button(composite, SWT.NONE);
    btnSignIt.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent ev) {
            final File inputFile = new File(textInputFile.getText());
            if (!inputFile.exists()) {
                putErrorDialog(new MessageFormat(BUNDLE.getString("JPKIPdfSignerGUI.fileNotFound"))
                        .format(new Object[] { inputFile.getPath() }));
                return;
            }
            final File outputFile = new File(textOutputFile.getText());
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Throwable cause = null;
                        try {
                            JPKIWrapper jpki = new JPKIWrapper();
                            PdfReader reader = new PdfReader(inputFile.getPath());
                            FileOutputStream fo = new FileOutputStream(outputFile);
                            JPKIPdfStamper stamper = JPKIPdfStamper.createSignature(reader, fo, BUNDLE, '\0');
                            JPKIPdfSignatureAppearance sa = stamper.getSignatureAppearance();
                            sa.setCrypto(jpki, JPKIPdfSignatureAppearance.WINCER_SIGNED);
                            stamper.close();
                        } catch (JPKIWrapperException e) {
                            cause = e.getCause();
                        } catch (ExceptionConverter e) {
                            cause = e.getCause().getCause();
                        }
                        if (cause != null) {
                            if (cause instanceof JPKICryptJNIException) {
                                switch (((JPKICryptJNIException) cause).getErrorCode()) {
                                case JPKICryptJNIException.JPKI_ERR_UNKNOWN:
                                    putErrorDialog(BUNDLE.getString("JPKIPdfSignerGUI.unknownError"));
                                    return;
                                case JPKICryptJNIException.JPKI_ERR_WINDOWS:
                                    switch (((JPKICryptJNIException) cause).getWinErrorCode()) {
                                    case JPKICryptJNIException.JPKI_WIN_CANCELLED_BY_USER:
                                        putErrorDialog(BUNDLE.getString("JPKIPdfSignerGUI.cancelledByUser"));
                                        break;
                                    case JPKICryptJNIException.JPKI_WIN_CHV_BLOCKED:
                                        putErrorDialog(BUNDLE.getString("JPKIPdfSignerGUI.cardLocked"));
                                        break;
                                    case JPKICryptJNIException.JPKI_WIN_NOT_READY:
                                        putErrorDialog(BUNDLE.getString("JPKIPdfSignerGUI.cardNotReady"));
                                        break;
                                    default:
                                        throw cause;
                                    }
                                    return;
                                default:
                                    throw cause;
                                }
                            } else {
                                throw cause;
                            }
                        }
                    } catch (final Throwable e) {
                        shlJpkiPdfSigner.getDisplay().asyncExec(new Runnable() {
                            public void run() {
                                java.io.StringWriter writer = new java.io.StringWriter();
                                e.printStackTrace(new java.io.PrintWriter(writer));
                                textMessages.insert(writer.toString());
                                textMessages.insert("\n");
                                try {
                                    writer.close();
                                } catch (IOException e) {
                                }
                            }
                        });
                        return;
                    }
                    putSuccessDialog(BUNDLE.getString("JPKIPdfSignerGUI.doneSuccessfully"));
                }
            }).start();
        }
    });
    btnSignIt.setText(BUNDLE.getString("JPKIPdfSignerGUI.btnSignIt.text"));
    Button btnClose = new Button(composite, SWT.NONE);
    btnClose.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent ev) {
            shlJpkiPdfSigner.close();
        }
    });
    btnClose.setText(BUNDLE.getString("JPKIPdfSignerGUI.btnClose.text")); //$NON-NLS-1$

    new Composite(sashForm, SWT.NONE);

    sashForm.setWeights(new int[] { 1, 2, 1 });

    textMessages = new Text(composite_2, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.MULTI);
    FormData fd_textMessages = new FormData();
    fd_textMessages.right = new FormAttachment(btnInputFile, 0, SWT.RIGHT);
    fd_textMessages.bottom = new FormAttachment(sashForm, -6);
    fd_textMessages.top = new FormAttachment(btnOutputFile, 6);
    fd_textMessages.left = new FormAttachment(0, 10);
    textMessages.setLayoutData(fd_textMessages);
}

From source file:learn.PdfRendererBasicFragment.java

License:Apache License

public void merge(int pageNum) {
    try {/*from  w  w w. j av a2  s . com*/
        Image image = Image.getInstance(signatureByte);
        pdfReader = new PdfReader(path);
        //fix y
        Matrix matrix = mSignatureImage.getImageMatrix();
        // Get the values of the matrix
        float[] values = new float[9];
        matrix.getValues(values);
        float relativeX = (mSignatureImage.getX() - values[2]) / values[0];
        float relativeY = (mSignatureImage.getY() - values[5]) / values[4];
        x = relativeX;
        y = relativeY;
        if (pageNum != -1) {
            y = pdfReader.getCropBox(pageNum).getHeight() - y;
            y -= mSign.getHeight();
        }
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(newP));
        if (pageNum == -1) {
            y = pdfReader.getCropBox(1).getHeight() - y;
            y -= mSign.getHeight();
            for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
                //put content under
                PdfContentByte content;// = pdfStamper.getUnderContent(i);
                // image.setAbsolutePosition(x, y);
                // content.addImage(image);

                //put content over
                content = pdfStamper.getOverContent(i);
                image.setAbsolutePosition(x, y);
                content.addImage(image);

                //Text over the existing page
                /*BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.WINANSI, BaseFont.EMBEDDED);
                content.beginText();
                content.setFontAndSize(bf, 18);
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Page No: " + i, 430, 15, 0);
                content.endText();*/
            }
        } else {
            PdfContentByte content = pdfStamper.getOverContent(pageNum);
            image.setAbsolutePosition(x, y);
            content.addImage(image);

        }
        pdfStamper.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:lecteur.Interface.java

private static String ReadPDF(String pdf_url) {
    String[] row;/*  w  w w . j a  v  a 2 s  .c  om*/
    ArrayList<Bilan> tabRubriqueBilanTotal = new ArrayList<>();
    ArrayList<Bilan> tabRubriqueBilan = null;
    System.out.println("ReadPDF");

    StringBuilder str = new StringBuilder();

    try {
        PdfReader reader = new PdfReader(pdf_url);
        int nbpage = reader.getNumberOfPages();
        System.out.println("Nombre de page = " + nbpage);
        //Recherche page BILAN - ACTIF
        //Recherche page BILAN - PASSIF
        //Recherche page 
        //pour chaque page, lire ligne.
        for (int i = 22; i <= 22; i++) {
            //for(int i=1;i<=nbpage;i++) {
            String str2 = PdfTextExtractor.getTextFromPage(reader, i);
            //System.out.println("STR2 = " + str2);
            //System.out.println("===========================");

            row = null;
            //Concatener les pages :
            //str.append(str2);
            //System.out.println("STR = " + str);

            //Appel fonction split chaque ligne de la page.
            row = splitPage(str2);
            System.out.println();
            System.out.println("\nnb row  traiter = " + row.length);

            //recherche de correspondance AA, AF, ect..
            //Recherche deux majuscules suivis d'espaces et nombre/espace/nombre
            //TODO
            //Gerer les cas o il n'y a pas de chiffre
            String pattern1 = "[A-Z]{2}";
            String pattern = "[A-Z]{2}\\p{Space}+\\d+\\p{Space}?\\d+";
            for (int j = 0; j < row.length; j++) {
                System.out.println("\nLigne  traiter AVANT FCT: " + row[j]);
                //TAB_BILAN par ligne
                tabRubriqueBilan = recherchebilan(row[j], pattern);
                for (int k = 0; k < tabRubriqueBilan.size(); k++) {
                    tabRubriqueBilanTotal.add(tabRubriqueBilan.get(k));
                }
            }

            for (int j = 0; j < tabRubriqueBilanTotal.size(); j++) {
                tabRubriqueBilanTotal.get(j).show();
            }

            System.out.println("TAILLE TAB PAR PAGE = " + tabRubriqueBilanTotal.size());
        }
        afficheResultat(tabRubriqueBilanTotal);

    } catch (Exception err) {
        err.printStackTrace();
    }
    return String.format("%s", str);
}

From source file:Logic.AddCover1.java

/**
 * Manipulates a PDF file src with the file dest as result
 * @param src the original PDF// w w w.ja v  a2s  .  c o m
 * @param dest the resulting PDF
 * @throws IOException
 * @throws DocumentException
 */
public void manipulatePdf(String src, String dest, String cov) throws IOException, DocumentException {
    PdfReader cover = new PdfReader(cov);
    PdfReader reader = new PdfReader(src);
    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest));
    document.open();
    copy.addDocument(cover);
    copy.addDocument(reader);

    document.close();
    cover.close();
    reader.close();
}

From source file:Logica.LogicaReserva.java

private void GenerarDocumento(Reserva nuevaReserva) throws IOException, DocumentException {
    //String dirPath = "C:\\";
    String fileName = "Base reserva.pdf";
    HashMap fieldsWithValues = new HashMap();
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    PdfReader reader = new PdfReader(fileName);
    PdfStamper stamper = new PdfStamper(reader, baosPDF);
    AcroFields form = stamper.getAcroFields();
    HashMap fields = (HashMap) form.getFields();
    Set keys = fields.keySet();//from   w  w  w . ja v a  2  s  .  c o m

    //Metodo que retorna map de datos que queremos obtener de objeto para agregar a PDF    
    fieldsWithValues = crearHashMapReserva(nuevaReserva, keys);

    //Iteracion sobre campos de pdf
    Iterator itr = keys.iterator();
    while (itr.hasNext()) {
        String fieldName = (String) itr.next();
        String fieldValue = fieldsWithValues.get(fieldName) != null ? (String) (fieldsWithValues.get(fieldName))
                : "";
        form.setField(fieldName, fieldValue);
        form.setFieldProperty(fieldName, "setfflags", PdfFormField.FF_READ_ONLY, null);

    }
    stamper.setFormFlattening(true);
    stamper.close();
    reader.close();

    //Guardando cambios
    String nombre;
    DateFormat fecha = new SimpleDateFormat("yyyy_MM_dd HH_mm_ss");
    nombre = fecha.format(nuevaReserva.getFechaHasta());
    String nombreydir = "Documentos\\Documento Reserva -" + nombre + "-.pdf";
    OutputStream pdf = new FileOutputStream(nombreydir);
    baosPDF.writeTo(pdf);
    pdf.close();

    Hilo h1 = new Hilo("email", nombreydir, nuevaReserva.getCliente().getCorreo());
    h1.start();

    try {
        File archivo = new File(nombreydir);
        Desktop.getDesktop().open(archivo);
    } catch (IOException ex) {
    }
    //EnvioEmail(nombreydir, nuevaReserva.getCliente().getCorreo());
}

From source file:managedbeans.descargas.PDFConversionDemo.java

public static void main(String[] args) {
    try {//from ww w .  ja v a 2s.c  om
        //Read file using PdfReader
        PdfReader pdfReader = new PdfReader("HelloWorld.pdf");

        //Modify file using PdfReader
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("HelloWorld-modified.pdf"));

        Image image = Image.getInstance("temp.png");
        image.scaleAbsolute(100, 50);
        image.setAbsolutePosition(100f, 700f);

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
            PdfContentByte content = pdfStamper.getUnderContent(i);
            content.addImage(image);
        }

        pdfStamper.close();

    } catch (IOException | DocumentException e) {
        logger.warn("failed to ...." + e);
    }
}

From source file:me.Aron.Heinecke.fbot.lib.Converter.java

License:Apache License

/***
 * Add a note to the bottom of a pdf file in italic font
 * @param rfile file to be read from/*from  www .java 2s.  c  om*/
 * @param wfile file to be written to
 * @param text text to add
 * @return path to the resulting pdf, null if it failed
 */
private String addPDFNote(File rfile, File wfile, String text) {
    try {
        PdfReader pdfReader = new PdfReader(rfile.getAbsolutePath());

        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(wfile));

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {

            PdfContentByte cb = pdfStamper.getUnderContent(i);

            BaseFont bf = BaseFont.createFont();
            bf.setPostscriptFontName("ITALIC");
            cb.beginText();
            cb.setFontAndSize(bf, 12);
            cb.setTextMatrix(10, 20);
            cb.showText(text);
            cb.endText();
        }

        pdfStamper.close();
        return wfile.getAbsolutePath();
    } catch (IOException | DocumentException e) {
        fbot.getLogger().exception("converter", e);
        return null;
    }
}

From source file:me.Aron.Heinecke.fbot.lib.Converter.java

License:Apache License

@Deprecated
public String ReadPdfFile(File file) throws IOException {
    StringBuilder text = new StringBuilder();

    if (file.exists()) {
        PdfReader pdfReader = new PdfReader(file.getAbsolutePath());

        for (int pageid = 1; pageid <= pdfReader.getNumberOfPages(); pageid++) {

            SimpleTextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
            String currentText = PdfTextExtractor.getTextFromPage(pdfReader, pageid, strategy);

            //currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
            text.append(currentText);/* w ww.j  a  v  a2  s  . c om*/
        }
        pdfReader.close();
    }
    return text.toString();
}