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:mergevoucher.MainJFrame.java

private void deletePages(File file, String str) throws IOException, DocumentException {
    //open the old pdf file and open a blank new one 
    String fullFileName = file.getPath();
    //System.out.println(fullFileName);
    PdfReader reader = new PdfReader(fullFileName);
    Document document = new Document(reader.getPageSizeWithRotation(1));
    String out = fullFileName.replaceFirst(".pdf", "(new).pdf");
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(out));
    document.open();/*from   ww  w.  j a  v a  2 s  .  c o m*/
    int pdfPageNumber = reader.getNumberOfPages(); //get pdf page number
    //change pageNumber string to int array
    Boolean[] preservePages = getPages(pdfPageNumber, str);
    //copy pages except need delete to new pdf file
    for (int i = 1; i <= pdfPageNumber; i++) {
        //filter not preserve pages 
        if (preservePages[i]) { //if preserve,copy;else bypass
            //String content = PdfTextExtractor.getTextFromPage(reader, i); //?i;
            copy.addPage(copy.getImportedPage(reader, i));
        }
    }
    System.out.println("New pdf file is:" + fullFileName.replaceFirst(".pdf", "(new).pdf"));
    //close files 
    reader.close();
    document.close();
    copy.close();
}

From source file:my.charpdf.DandDcharPDFUI.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    String inputFile;// www . j  av  a 2s. co  m
    inputFile = jTextField1.getText().replace("\n", "").replace("\r", "");
    String pcName = "";
    String pcRace = "";
    String pcAlign = "";
    String pcBackG = "";
    String pcExp = "";
    String pcProfBonus = "";
    String pcStrScore = "";
    String pcStrMod = "";
    String pcDexScore = "";
    String pcDexMod = "";
    String pcConScore = "";
    String pcConMod = "";
    String pcIntScore = "";
    String pcIntMod = "";
    String pcWisScore = "";
    String pcWisMod = "";
    String pcChaScore = "";
    String pcChaMod = "";
    String pcClassLevel = "";
    String pcPerc = "";
    if (!inputFile.equals("")) {
        try {
            Builder parser = new Builder();
            Document doc = parser.build("file:///" + inputFile);

            Element root = doc.getRootElement();
            Elements character = root.getChildElements();

            pcName = character.get(0).getFirstChildElement("name").getValue();
            pcRace = character.get(0).getFirstChildElement("race").getValue();
            pcExp = character.get(0).getFirstChildElement("exp").getValue();
            pcAlign = character.get(0).getFirstChildElement("alignment").getValue();
            pcBackG = character.get(0).getFirstChildElement("background").getValue();
            pcProfBonus = character.get(0).getFirstChildElement("profbonus").getValue();
            pcPerc = character.get(0).getFirstChildElement("perception").getValue();

            //Integer numChildren = character.get(0).getChildCount();
            //System.out.println(numChildren);

            Elements pcAttrs = character.get(0).getChildElements("abilities").get(0).getChildElements();
            Elements pcClasses = character.get(0).getChildElements("classes").get(0).getChildElements();

            for (int i = 0; i < pcAttrs.size(); i++) {
                if (pcAttrs.get(i).getLocalName().equals("strength")) {
                    pcStrScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcStrMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("dexterity")) {
                    pcDexScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcDexMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("constitution")) {
                    pcConScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcConMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("intelligence")) {
                    pcIntScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcIntMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("wisdom")) {
                    pcWisScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcWisMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                } else if (pcAttrs.get(i).getLocalName().equals("charisma")) {
                    pcChaScore = pcAttrs.get(i).getChildElements("score").get(0).getValue();
                    pcChaMod = pcAttrs.get(i).getChildElements("bonus").get(0).getValue();
                }
            }

            for (int i = 0; i < pcClasses.size(); i++) {
                // Gets the list of classes
                //System.out.println(pcClasses.get(i).getLocalName());
                String tempClass = pcClasses.get(i).getChildElements("name").get(0).getValue();
                String tempLevel = pcClasses.get(i).getChildElements("level").get(0).getValue();
                pcClassLevel += tempClass + " " + tempLevel + " / ";
            }
            pcClassLevel = pcClassLevel.substring(0, pcClassLevel.length() - 2);

            //for(i = 0; i < numClasses; i++) {
            //    System.out.println(charac);
            //}

            String inputTemplate = "resources/DandD5e-template.pdf";

            String outputPDF = "resources/" + pcName + ".pdf";

            PdfReader reader = new PdfReader(inputTemplate);
            PdfStamper stamper;
            stamper = new PdfStamper(reader, new FileOutputStream(outputPDF));
            AcroFields form = reader.getAcroFields();

            Set<String> fields = form.getFields().keySet();

            for (String key : fields) {
                //System.out.println(key);
                switch (form.getFieldType(key)) {
                case AcroFields.FIELD_TYPE_CHECKBOX:
                    //System.out.println(key + ": Checkbox");
                    break;
                case AcroFields.FIELD_TYPE_COMBO:
                    //System.out.println(key + ": Combo");
                    break;
                case AcroFields.FIELD_TYPE_LIST:
                    //System.out.println(key + ": List");
                    break;
                case AcroFields.FIELD_TYPE_NONE:
                    //System.out.println(key + ": None");
                    break;
                case AcroFields.FIELD_TYPE_PUSHBUTTON:
                    //System.out.println(key + ": Pushbutton");
                    break;
                case AcroFields.FIELD_TYPE_RADIOBUTTON:
                    //System.out.println(key + ": Radio");
                    break;
                case AcroFields.FIELD_TYPE_SIGNATURE:
                    //System.out.println(key + ": Signature");
                    break;
                case AcroFields.FIELD_TYPE_TEXT:
                    //System.out.println(key + ": Text");
                    break;
                default:
                    //System.out.println(key + ": ???");
                }
            }
            stamper.getAcroFields().setField("Race ", pcRace);
            stamper.getAcroFields().setField("CharacterName", pcName);
            stamper.getAcroFields().setField("XP", pcExp);
            stamper.getAcroFields().setField("Alignment", pcAlign);
            stamper.getAcroFields().setField("Background", pcBackG);
            int tempPB = Integer.parseInt(pcProfBonus);
            if (tempPB > 0) {
                pcProfBonus = "+" + pcProfBonus;
            }
            stamper.getAcroFields().setField("ProfBonus", pcProfBonus);

            //Attributes
            stamper.getAcroFields().setField("STR", pcStrScore);
            stamper.getAcroFields().setField("STRmod", pcStrMod);
            stamper.getAcroFields().setField("DEX", pcDexScore);
            stamper.getAcroFields().setField("DEXmod ", pcDexMod);
            stamper.getAcroFields().setField("CON", pcConScore);
            stamper.getAcroFields().setField("CONmod", pcConMod);
            stamper.getAcroFields().setField("INT", pcIntScore);
            stamper.getAcroFields().setField("INTmod", pcIntMod);
            stamper.getAcroFields().setField("WIS", pcWisScore);
            stamper.getAcroFields().setField("WISmod", pcWisMod);
            stamper.getAcroFields().setField("CHA", pcChaScore);
            stamper.getAcroFields().setField("CHamod", pcChaMod);

            stamper.getAcroFields().setField("ClassLevel", pcClassLevel);
            stamper.getAcroFields().setField("Passive", pcPerc);

            stamper.close();
            reader.close();
        } catch (java.io.IOException | DocumentException e) {
            System.err.println("1st Catch, that didn't go well: " + e.getMessage());
        } catch (ParsingException e) {
            System.err.println("2nd Catch, that didn't go well: " + e.getMessage());
        }
    }
}

From source file:nakpil.proccess.Form2316Process.java

@Override
public void run() {
    try {/*from  ww w.j  a v a 2s .com*/

        reset();

        if (Datas.size() > 1) {
            Bar.setMaximum(Datas.size());
            int i = 0;
            document = new com.itextpdf.text.Document();
            oStream_bulk = new FileOutputStream(Output_batch + File.separator + Datas.get(0).getSequenceID()
                    + "-" + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf");
            PDFcopy = new PdfCopy(document, oStream_bulk);
            document.open();
            PDialog.printResult("Starting Module Services.");
            for (BIRAccount Temp : Datas) {
                i++;
                Bar.setString("Encoding " + Temp.getFullname());

                //Open Template
                Template = new WorkBook();
                iStream = new FileInputStream(Source);
                Template.readXLSB(iStream);

                //Forming Data Encode
                BIR_Form = new Data2316();
                BIR_Form.setBIRAccount(Temp, Personel);
                BIR_Form.encodeTo(Template);

                //Prepare Pdf Output
                Output = ((Output.isEmpty())
                        ? System.getProperty("user.home") + File.separator + "Desktop" + File.separator
                                + "BIR2316" + File.separator + Temp.getTinNumber() + ".pdf"
                        : Output + File.separator + Temp.getTinNumber() + ".pdf");
                oStream = new FileOutputStream(Output);
                Bar.setString("Exporting PDF : " + Output);
                Template.exportPDF(oStream);

                //Close Exported PDF
                oStream.flush();
                oStream.close();
                oStream = null;

                //Patch Document
                PDFreader = new PdfReader(Output);
                PDFcopy.addDocument(PDFreader);
                PDFcopy.freeReader(PDFreader);
                PDFcopy.flush();

                //Close Copied PDF
                PDFreader.close();
                PDFreader = null;

                //Close Template
                Template.dispose();
                Template = null;
                iStream.close();
                iStream = null;

                Bar.setValue(i);
                PDialog.printResult(Temp.getFullname() + " Encoding completed...");
                System.gc();
            }
            PDFcopy.close();
            document.close();
            oStream_bulk.flush();
            oStream_bulk.close();
            PDFcopy = null;
            oStream = null;
            if (Print) {
                if (Copy == 1) {
                    if (printCMD.isEmpty()) {
                        PrintProgram = com.lowagie.tools.Executable.printDocumentSilent(
                                Output_batch + File.separator + Datas.get(0).getSequenceID() + "-"
                                        + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf",
                                false);
                    } else {
                        PrintProgram = Runtime.getRuntime()
                                .exec(printCMD + ((printPreARG.isEmpty()) ? "" : " " + printPreARG + " ") + "\""
                                        + Output_batch + File.separator + Datas.get(0).getSequenceID() + "-"
                                        + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf\""
                                        + ((printPostARG.isEmpty()) ? "" : " " + printPostARG));
                    }
                    Bar.setString("Print Job Sent.");
                } else if (Copy > 1) {
                    for (int c = 1; c <= Copy; c++) {
                        if (printCMD.isEmpty()) {
                            PrintProgram = com.lowagie.tools.Executable
                                    .printDocumentSilent(
                                            Output_batch + File.separator + Datas.get(0).getSequenceID() + "-"
                                                    + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf",
                                            false);
                        } else {
                            PrintProgram = Runtime.getRuntime()
                                    .exec(printCMD + ((printPreARG.isEmpty()) ? "" : " " + printPreARG + " ")
                                            + "\"" + Output_batch + File.separator
                                            + Datas.get(0).getSequenceID() + "-"
                                            + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf\""
                                            + ((printPostARG.isEmpty()) ? "" : " " + printPostARG));

                        }
                        Bar.setString("Print Job [" + i + "] Sent.");
                    }

                }
            }
            Bar.setString("Finished");
            Thread.sleep(2000);
            PDialog.stop();
        } else if (Datas.size() == 1) {
            Bar.setMaximum(2);
            Bar.setValue(1);
            Bar.setString("Encoding " + Datas.get(0).getFullname());

            //Load Template
            Template = new WorkBook();
            iStream = new FileInputStream(Source);
            Template.readXLSX(iStream);

            //Encode Data
            BIR_Form = new Data2316();
            BIR_Form.setBIRAccount(Datas.get(0), Personel);
            BIR_Form.encodeTo(Template);

            //Prepare PDF Export;
            Output = ((Output.isEmpty())
                    ? System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "BIR2316"
                            + File.separator + Datas.get(0).getTinNumber() + ".pdf"
                    : Output + File.separator + Datas.get(0).getTinNumber() + ".pdf");
            oStream = new FileOutputStream(Output);
            if (Print) {
                Bar.setString("Printing 1 of 1");
                Template.setPrintNumberOfCopies(Copy);
                Template.print();
            }
            Bar.setString("Exporting PDF : " + Output);
            Template.exportPDF(oStream);

            Bar.setValue(2);
            Bar.setString("Process Done");
            Thread.sleep(2000);
            PDialog.stop();
        }
    } catch (Exception er) {
        Bar.setString(er.toString());
    } finally {
        try {
            if (iStream != null) {
                iStream.close();
            }
            if (oStream != null) {
                oStream.flush();
                oStream.close();
            }
            if (PDFcopy != null) {
                PDFcopy.close();
                document.close();
                oStream_bulk.flush();
                oStream_bulk.close();
            }
            BIR_Form = null;
            Datas = null;
            Template = null;
            iStream = null;
            oStream = null;
            PDFcopy = null;
            oStream = null;
            document = null;
            System.gc();
        } catch (Exception er) {
            Bar.setString(er.toString());
        }
    }
}

From source file:net.digitstar.vanadio.AbstractReportPdf.java

License:Apache License

private void closeDocument(Document document, ByteArrayOutputStream baos, OutputStream out) {
    if (document != null) {
        document.close();//w w  w.  j av  a 2 s  . co  m
        PdfStamper writer = null;
        try {
            PdfReader reader = new PdfReader(baos.toByteArray());
            writer = new PdfStamper(reader, out);

            afterCloseDocument(document, reader, writer);
        } catch (IOException e) {
            /**/ } catch (DocumentException e) {
            /**/ } finally {
            if (writer != null)
                try {
                    writer.close();
                } catch (DocumentException e) {
                    /**/} catch (IOException e) {
                    /**/}
        }
    }
}

From source file:net.ionescu.jhocr2pdf.Jhocr2pdf.java

License:Open Source License

/**
 * @param args/* w  w  w .j a  va2 s.  c  o  m*/
 * The arguments are:
 *  [options] output_pdf
 * The name of the output PDF file with the added OCR information must be the last argument
 * Other 
 * flags:
 *   -i pdf_file PDF file containing the TIFF images
 *   -hocr html_file hOCR file generated by Tesseract 
 *   -visible render the text above the image (mostry for debugging)
 *   -font font_path  path to the font file to use
 *   -hocrnameformat string to use to construct the name of the hocr file depending on page number
 *
 * Usage example:
 * java -jar jhorc2pdf.jar -font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf -i input.pdf -hocr input.html output.pdf
 *
 * @throws SAXException
 * @throws IOException
 * @throws DocumentException
 */
public static void main(String[] args) throws SAXException, IOException, DocumentException {
    /*
     * process input parameters
     * 
     * -visible -font font_path inputPDF inputOCR outputPDF
     */
    boolean visible = false;
    String fontPath = null;
    String fileNameFormat = null;
    String inputPDF = null;
    String inputHOCR = null;
    String outputPDF = null;

    for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("-")) {
            switch (args[i]) {

            case "-visible":
                visible = true;
                break;

            case "-font":
                fontPath = args[++i];
                break;

            case "-hocrnameformat":
                fileNameFormat = args[++i];
                break;

            case "-i":
                inputPDF = args[++i];
                break;

            case "-hocr":
                inputHOCR = args[++i];
                break;

            default:
                System.err.println("Invalid parameter: " + args[i]);
                System.exit(1);
            }
        } else {
            if (i < args.length - 1) {
                System.err.println("Ouput file name should be the last argument");
                System.exit(1);
            }
            outputPDF = args[i];
        }
    }

    log.fine("load the PDF file, initialize the Stamper");
    PdfReader reader = new PdfReader(inputPDF);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPDF));

    Map<String, String> info = reader.getInfo();
    info.put("Title", new File(outputPDF).getName());
    stamper.setMoreInfo(info);

    Jhocr2pdf ocrStamp = new Jhocr2pdf(stamper, visible, fontPath);
    if (null != fileNameFormat) {
        log.fine("iterate through all the pages looking for separate hocr files");
        for (int i = 1, maxPages = reader.getNumberOfPages() + 1; i < maxPages; i++) {
            String hocrFileName = String.format(fileNameFormat, i);
            try {
                ocrStamp.parse(hocrFileName, i);
            } catch (SAXException saxException) {
                System.err.println("Error processing hocr file: " + hocrFileName);
                throw saxException;
            }
        }
    } else {
        ocrStamp.parse(inputHOCR, -1);
    }
    stamper.close();
}

From source file:net.japt.transpdf.TransPDF.java

License:Apache License

/**
 * Translate English PDF to Spanish Text
 * /*from w w  w. java  2  s. c  om*/
 * @param pdfFile String Path of the PDF Document
 * @param textFile String Path of the Translated Text Document
 */
public static void translate(String pdfFile, String textFile) {
    try {
        PdfReader pdfReader = new PdfReader(pdfFile);
        FileWriter transTxtFile = new FileWriter(textFile, true);

        int numPages = pdfReader.getNumberOfPages();

        Translator translate = Translator.getInstance();

        for (int i = 1; i <= numPages; i++) {
            // Pages
            String pageText = com.itextpdf.text.pdf.parser.PdfTextExtractor.getTextFromPage(pdfReader, i);

            // Paragraph
            String[] lines = pageText.split("\n");

            if (lines.length == 0) {
                lines = new String[1];
                lines[0] = pageText;
            }

            for (int nl = 0; nl < lines.length; nl++) {
                String transLine = "";

                // Points
                String[] points = lines[nl].split("\\.");

                if (points.length == 0) {
                    points = new String[1];
                    points[0] = lines[nl];
                }

                for (int np = 0; np < points.length; np++) {
                    // Commas
                    String[] commas = points[np].split(",");

                    if (commas.length == 0) {
                        commas = new String[1];
                        commas[0] = points[np];
                    }

                    for (int nc = 0; nc < commas.length; nc++) {
                        if (commas[nc].length() > 0) {
                            String translatedText = translate.translate(commas[nc], Language.ENGLISH,
                                    Language.SPANISH);
                            transLine = transLine + " " + translatedText;
                        }
                    }
                }

                transTxtFile.write(transLine + "\n");
            }
        }

        transTxtFile.flush();
        transTxtFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.pflaeging.PortableSigner.PDFSigner.java

License:Open Source License

/** Creates a new instance of DoSignPDF */
public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password,
        Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment,
        String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin,
        float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException {
    try {//from  ww w .  jav  a  2s  .co m
        //System.out.println("-> DoSignPDF <-");
        //System.out.println("Eingabedatei: " + pdfInputFileName);
        //System.out.println("Ausgabedatei: " + pdfOutputFileName);
        //System.out.println("Signaturdatei: " + pkcs12FileName);
        //System.out.println("Signaturblock?: " + signText);
        //System.out.println("Sprache der Blocks: " + signLanguage);
        //System.out.println("Signaturlogo: " + sigLogo);
        System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin);
        Rectangle signatureBlock;

        java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);

        pkcs12 = new GetPKCS12(pkcs12FileName, password);

        PdfReader reader = null;
        try {
            //                System.out.println("Password:" + ownerPassword.toString());
            if (ownerPassword == null)
                reader = new PdfReader(pdfInputFileName);
            else
                reader = new PdfReader(pdfInputFileName, ownerPassword);
        } catch (IOException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle(
                "net/pflaeging/PortableSigner/i18n").getString(
                "CouldNotBeOpened"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeOpened"), true, e.getLocalizedMessage());
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pdfOutputFileName);
        } catch (FileNotFoundException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeWritten"), true, e.getLocalizedMessage());

        }
        PdfStamper stp = null;
        try {
            Date datum = new Date(System.currentTimeMillis());

            int pages = reader.getNumberOfPages();

            Rectangle size = reader.getPageSize(pages);
            stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
            HashMap<String, String> pdfInfo = reader.getInfo();
            // thanks to Markus Feisst
            String pdfInfoProducer = "";

            if (pdfInfo.get("Producer") != null) {
                pdfInfoProducer = pdfInfo.get("Producer").toString();
                pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")";
            } else {
                pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")";
            }
            pdfInfo.put("Producer", pdfInfoProducer);
            //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString());
            stp.setMoreInfo(pdfInfo);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XmpWriter xmp = new XmpWriter(baos, pdfInfo);
            xmp.close();
            stp.setXmpMetadata(baos.toByteArray());
            if (signText) {
                String greet, signator, datestr, ca, serial, special, note, urn, urnvalue;
                int specialcount = 0;
                int sigpage;
                int rightMarginPT, leftMarginPT;
                float verticalPositionPT;
                ResourceBundle block = ResourceBundle
                        .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage);
                greet = block.getString("greeting");
                signator = block.getString("signator");
                datestr = block.getString("date");
                ca = block.getString("issuer");
                serial = block.getString("serial");
                special = block.getString("special");
                note = block.getString("note");
                urn = block.getString("urn");
                urnvalue = block.getString("urnvalue");

                //sigcomment = block.getString(signLanguage + "-comment");
                // upper y
                float topy = size.getTop();
                System.err.println("Top: " + topy * ptToCm);
                // right x
                float rightx = size.getRight();
                System.err.println("Right: " + rightx * ptToCm);
                if (!noExtraPage) {
                    sigpage = pages + 1;
                    stp.insertPage(sigpage, size);
                    // 30pt left, 30pt right, 20pt from top
                    rightMarginPT = 30;
                    leftMarginPT = 30;
                    verticalPositionPT = topy - 20;
                } else {
                    if (signLastPage) {
                        sigpage = pages;
                    } else {
                        sigpage = 1;
                    }
                    System.err.println("Page: " + sigpage);
                    rightMarginPT = Math.round(rightMargin / ptToCm);
                    leftMarginPT = Math.round(leftMargin / ptToCm);
                    verticalPositionPT = topy - Math.round(verticalPos / ptToCm);
                }
                if (!GetPKCS12.atEgovOID.equals("")) {
                    specialcount = 1;
                }
                PdfContentByte content = stp.getOverContent(sigpage);

                float[] cellsize = new float[2];
                cellsize[0] = 100f;
                // rightx = width of page
                // 60 = 2x30 margins
                // cellsize[0] = description row
                // cellsize[1] = 0
                // 70 = logo width
                cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70;

                // Pagetable = Greeting, signatureblock, comment
                // sigpagetable = outer table
                //      consist: greetingcell, signatureblock , commentcell
                PdfPTable signatureBlockCompleteTable = new PdfPTable(2);
                PdfPTable signatureTextTable = new PdfPTable(2);
                PdfPCell signatureBlockHeadingCell = new PdfPCell(
                        new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12))));
                signatureBlockHeadingCell.setPaddingBottom(5);
                signatureBlockHeadingCell.setColspan(2);
                signatureBlockHeadingCell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(signatureBlockHeadingCell);

                // inner table start
                // Line 1
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10))));
                // Line 2
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 3
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10))));
                // Line 4
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(new Paragraph(
                        new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 5
                if (specialcount == 1) {
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10))));
                }
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable
                        .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10))));
                signatureTextTable.setTotalWidth(cellsize);
                System.err.println(
                        "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm);
                // inner table end

                signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                Image logo;
                //                     System.out.println("Logo:" + sigLogo + ":");
                if (sigLogo == null || "".equals(sigLogo)) {
                    logo = Image.getInstance(
                            getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png"));
                } else {
                    logo = Image.getInstance(sigLogo);
                }

                PdfPCell logocell = new PdfPCell();
                logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                logocell.setImage(logo);
                signatureBlockCompleteTable.addCell(logocell);
                PdfPCell incell = new PdfPCell(signatureTextTable);
                incell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(incell);
                PdfPCell commentcell = new PdfPCell(
                        new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10))));
                PdfPCell notecell = new PdfPCell(
                        new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                //commentcell.setPaddingTop(10);
                //commentcell.setColspan(2);
                // commentcell.setBorderWidth(0f);
                if (!sigComment.equals("")) {
                    signatureBlockCompleteTable.addCell(notecell);
                    signatureBlockCompleteTable.addCell(commentcell);
                }
                float[] cells = { 70, cellsize[0] + cellsize[1] };
                signatureBlockCompleteTable.setTotalWidth(cells);
                System.err.println(
                        "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm);
                signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT,
                        verticalPositionPT, content);
                System.err.println(
                        "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm);
                signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20,
                        topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20);
                //                    //////
                //                    AcroFields af = reader.getAcroFields();
                //                    ArrayList names = af.getSignatureNames();
                //                    for (int k = 0; k < names.size(); ++k) {
                //                        String name = (String) names.get(k);
                //                        System.out.println("Signature name: " + name);
                //                        System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name));
                //                        System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
                //                        PdfPKCS7 pk = af.verifySignature(name);
                //                        X509Certificate tempsigner = pk.getSigningCertificate();
                //                        Calendar cal = pk.getSignDate();
                //                        Certificate pkc[] = pk.getCertificates();
                //                        java.util.ResourceBundle tempoid =
                //                                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID");
                //                        String tmpEgovOID = "";
                //
                //                        for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) {
                //                            String element = o.nextElement();
                //                            // System.out.println(element + ":" + oid.getString(element));
                //                            if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) {
                //                                if (!tmpEgovOID.equals("")) {
                //                                    tmpEgovOID += ", ";
                //                                }
                //                                tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")";
                //                            }
                //                        }
                //                        //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
                //                        System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString());
                //                        System.out.println("\tDatum: " + cal.getTime().toString());
                //                        System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString());
                //                        System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber());
                //                        if (!tmpEgovOID.equals("")) {
                //                            System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID);
                //                        }
                //                        System.out.println("\n");
                //                        System.out.println("\tDocument modified: " + !pk.verify());
                ////                Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
                ////                if (fails == null) {
                ////                    System.out.println("\tCertificates verified against the KeyStore");
                ////                } else {
                ////                    System.out.println("\tCertificate failed: " + fails[1]);
                ////                }
                //                    }
                //
                //                //////
            } else {
                signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition
            }
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            //                sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null,
            //                        PdfSignatureAppearance.WINCER_SIGNED );
            sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null);
            sap.setReason(signReason);
            sap.setLocation(signLocation);
            //                if (signText) {
            //                    sap.setVisibleSignature(signatureBlock,
            //                            pages + 1, "PortableSigner");
            //                }
            if (finalize) {
                sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
            } else {
                sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
            }
            stp.close();

            /* MODIFY BY: Denis Torresan
            Main.setResult(
              java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"),
              false,
              "");
                */

        } catch (Exception e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage());

        }
    } catch (KeyStoreException kse) {

        /* MODIFY BY: Denis Torresan
         Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"),
            true, kse.getLocalizedMessage());
         */

        throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage());

    }
}

From source file:net.sf.regain.crawler.preparator.PdfItextPreparator.java

License:Open Source License

/**
 * Prpariert ein Dokument fr die Indizierung.
 *
 * @param rawDocument Das zu prpariernde Dokument.
 * @throws net.sf.regain.RegainException Wenn die Prparation fehl schlug.
 *//* www . ja  v a 2 s.c  om*/
@SuppressWarnings("unchecked")
public void prepare(RawDocument rawDocument) throws RegainException {
    String url = rawDocument.getUrl();

    InputStream stream = null;
    PdfReader reader = null;

    try {
        // Create a InputStream that reads the content.
        stream = rawDocument.getContentAsStream();

        // Parse the content
        reader = new PdfReader(stream);
        if (reader.isEncrypted()) {
            reader = new PdfReader(stream, OWNER_PASSWORD);
        }
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);

        TextExtractionStrategy strategy;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
            stringBuilder.append(strategy.getResultantText());

        }

        setCleanedContent(stringBuilder.toString());

        // Get metadata
        Map<String, String> info = reader.getInfo();

        StringBuilder metaData = new StringBuilder();
        metaData.append("p.");
        metaData.append(Integer.toString(reader.getNumberOfPages()));
        metaData.append(" ");

        // Check if fields are null
        String author = info.get("Author");
        String creator = info.get("Creator");
        String subject = info.get("Subject");
        String keywords = info.get("Keywords");
        String title = info.get("Title");

        if (author != null) {
            metaData.append(author);
            metaData.append(" ");
        }
        if (creator != null) {
            metaData.append(creator);
            metaData.append(" ");
        }
        if (subject != null) {
            metaData.append(subject);
            metaData.append(" ");
        }
        if (keywords != null) {
            metaData.append(keywords);
            metaData.append(" ");
        }

        if (title != null) {
            setTitle(title);
        }

        setCleanedMetaData(metaData.toString());
        if (log.isDebugEnabled()) {
            log.debug("Extracted meta data ::" + getCleanedMetaData() + ":: from " + rawDocument.getUrl());
        }

    } catch (IOException exc) {
        throw new RegainException("Error reading document: " + url, exc);
    } catch (Exception exc) {
        // They didn't supply a password and the default of "" was wrong.
        throw new RegainException("Unknown error parsing document: " + url, exc);

    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception exc) {
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception exc) {
            }
        }
    }
}

From source file:no.dusken.aranea.admin.control.issue.IssueIndexer.java

License:Apache License

private void indexIssue(Issue issue) throws IOException {
    if (pagesNotPreviouslyStored(issue)) {
        File pdfFile = getPdfFile(issue);
        if (pdfFile.exists()) {
            PdfReader pdfReader = new PdfReader(new FileInputStream(pdfFile));
            addPagesToIssue(pdfReader, issue);
        }/*from   w  w  w.jav  a2  s. c o  m*/
    }
}

From source file:nz.ac.waikato.cms.doc.HyperLinkGrades.java

License:Open Source License

/**
 * Adds the index with locations to the existing PDF.
 *
 * @param locations   the locations to index
 * @param input   the input PDF//from w  ww.j  av a2s .  com
 * @param output   the output PDF
 * @return      true if successfully generated
 */
public static boolean addIndex(List<Location> locations, File input, File output) {
    try {
        // copy pages, add target
        PdfReader reader = new PdfReader(input.getAbsolutePath());
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(output.getAbsolutePath()));
        document.open();
        PdfContentByte canvas = writer.getDirectContent();
        PdfImportedPage page;
        float height = 0;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            document.newPage();
            page = writer.getImportedPage(reader, i);
            canvas.addTemplate(page, 1f, 0, 0, 1, 0, 0);
            Chunk loc = new Chunk(" ");
            loc.setLocalDestination("loc" + i);
            height = page.getHeight();
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(loc), 50, height - 50, 0);
        }
        // add index
        for (int i = 0; i < locations.size(); i++) {
            Location loc = locations.get(i);
            if (i % MAX_ITEMS_PER_PAGE == 0)
                document.newPage();
            String text = loc.getID() + " " + (loc.getName() == null ? "???" : loc.getName());
            Chunk chunk = new Chunk("Page " + (loc.getPage() + 1) + ": " + text);
            chunk.setAction(PdfAction.gotoLocalPage("loc" + (loc.getPage() + 1), false));
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(chunk), 50,
                    height - 100 - (i % MAX_ITEMS_PER_PAGE) * 20, 0);
        }
        document.close();

        return true;
    } catch (Exception e) {
        System.err.println("Failed to overlay locations!");
        e.printStackTrace();
        return false;
    }
}