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

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

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the reader, and any underlying stream or data source used to create the reader

Usage

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  av  a 2  s  .  c  o  m*/
        }
        pdfReader.close();
    }
    return text.toString();
}

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();//w  w  w .j  a  v a 2 s  .  com
    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;/*from w ww . j  ava  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:net.algem.edition.PdfHandler.java

License:Open Source License

public void createPdf(String fileName, ByteArrayOutputStream out, short templateType)
        throws IOException, DocumentException {
    try {//  w  ww  .j  a v a 2  s  .  co  m
        File tmpFile = File.createTempFile(fileName, ".pdf");
        final String target = tmpFile.getPath();
        PageTemplate pt = getTemplate(templateType);
        PdfReader reader = new com.itextpdf.text.pdf.PdfReader(out.toByteArray());
        if (pt != null) {
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(target));
            //        PdfStamper stamper = new PdfStamper(reader, new PrintStream(new FileOutputStream(target), true, "UTF-8"));
            PdfReader model = new com.itextpdf.text.pdf.PdfReader(pt.getContent());
            PdfImportedPage importedPage = stamper.getImportedPage(model, 1);
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                PdfContentByte canvas = stamper.getUnderContent(i);
                canvas.addTemplate(importedPage, 0, 0);
            }

            stamper.getWriter().freeReader(model);
            model.close();
            stamper.close();
        } else {
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(target));
            //PdfStamper stamper = new PdfStamper(reader, new PrintStream(new FileOutputStream(target), true, "UTF-8"));
            stamper.close();
        }

        preview(target, null);
    } catch (SQLException ex) {
        GemLogger.logException(ex);
    }
}

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.
 *//*from w  w w .j  av  a  2s  . 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:nz.ac.waikato.cms.doc.OverlayFilename.java

License:Open Source License

/**
 * Performs the overlay./*w  w w.  java2  s  .  c om*/
 *
 * @param input   the input file/dir
 * @param output   the output file/dir
 * @param vpos   the vertical position
 * @param hpos   the horizontal position
 * @param stripPath   whether to strip the path
 * @param stripExt   whether to strip the extension
 * @param pages   the array of pages (1-based) to add the overlay to, null for all
 * @param evenPages   whether to enforce even pages in the document
 * @return      true if successfully overlay
 */
public boolean overlay(File input, File output, int vpos, int hpos, boolean stripPath, boolean stripExt,
        int[] pages, boolean evenPages) {
    PdfReader reader;
    PdfStamper stamper;
    FileOutputStream fos;
    PdfContentByte canvas;
    int i;
    String text;
    int numPages;
    File tmpFile;
    Document document;
    PdfWriter writer;
    PdfImportedPage page;
    PdfContentByte cb;

    reader = null;
    stamper = null;
    fos = null;
    numPages = -1;
    try {
        reader = new PdfReader(input.getAbsolutePath());
        fos = new FileOutputStream(output.getAbsolutePath());
        stamper = new PdfStamper(reader, fos);
        numPages = reader.getNumberOfPages();
        if (pages == null) {
            pages = new int[reader.getNumberOfPages()];
            for (i = 0; i < pages.length; i++)
                pages[i] = i + 1;
        }

        if (stripPath)
            text = input.getName();
        else
            text = input.getAbsolutePath();
        if (stripExt)
            text = text.replaceFirst("\\.[pP][dD][fF]$", "");

        for (i = 0; i < pages.length; i++) {
            canvas = stamper.getOverContent(pages[i]);
            ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Paragraph(text), hpos, vpos, 0.0f);
        }
    } catch (Exception e) {
        System.err.println("Failed to process " + input + ":");
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (stamper != null)
                stamper.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (reader != null)
                reader.close();
        } catch (Exception e) {
            // ignored
        }
        try {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        } catch (Exception e) {
            // ignored
        }
    }

    // enforce even pages?
    if (evenPages && (numPages > 0) && (numPages % 2 == 1)) {
        reader = null;
        fos = null;
        writer = null;
        tmpFile = new File(output.getAbsolutePath() + "tmp");
        try {
            if (!output.renameTo(tmpFile)) {
                System.err.println("Failed to rename '" + output + "' to '" + tmpFile + "'!");
                return false;
            }
            reader = new PdfReader(tmpFile.getAbsolutePath());
            document = new Document(reader.getPageSize(1));
            fos = new FileOutputStream(output.getAbsoluteFile());
            writer = PdfWriter.getInstance(document, fos);
            document.open();
            document.addCreationDate();
            document.addAuthor(System.getProperty("user.name"));
            cb = writer.getDirectContent();
            for (i = 0; i < reader.getNumberOfPages(); i++) {
                page = writer.getImportedPage(reader, i + 1);
                document.newPage();
                cb.addTemplate(page, 0, 0);
            }
            document.newPage();
            document.add(new Paragraph(" ")); // fake content
            document.close();
        } catch (Exception e) {
            System.err.println("Failed to process " + tmpFile + ":");
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
            } catch (Exception e) {
                // ignored
            }
            try {
                if (reader != null)
                    reader.close();
            } catch (Exception e) {
                // ignored
            }
            try {
                if (writer != null)
                    writer.close();
            } catch (Exception e) {
                // ignored
            }
            if (tmpFile.exists()) {
                try {
                    tmpFile.delete();
                } catch (Exception e) {
                    // ignored
                }
            }
        }
    }

    return true;
}

From source file:om.edu.squ.squportal.portlet.tsurvey.dao.pdf.TeachingSurveyPdfImpl.java

License:Open Source License

/**
 * /*w w  w.j  a v  a2  s. co m*/
 * method name  : getPdfSurveyAnalysis
 * @param object
 * @param semesterYear
 * @param questionByYear
 * @param questionSetNo
 * @param byos
 * @param inputStream
 * @param res
 * @return
 * @throws DocumentException
 * @throws IOException
 * TeachingSurveyPdfImpl
 * return type  : OutputStream
 * 
 * purpose      : Generate PDF content
 *
 * Date          :   Mar 28, 2016 7:21:04 PM
 */
public OutputStream getPdfSurveyAnalysis(Object object, String semesterYear, String questionByYear,
        int questionSetNo, ByteArrayOutputStream byos, InputStream inputStream, ResourceResponse res)
        throws DocumentException, IOException {

    Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 10, BaseColor.BLACK);

    PdfReader pdfTemplate = new PdfReader(inputStream);
    PdfStamper pdfStamper = new PdfStamper(pdfTemplate, byos);
    Survey survey = (Survey) object;
    String sectionNos = "";
    String seatsTaken = "";
    DecimalFormat formatter = new DecimalFormat("###.##");

    String RIGHT = Constants.RIGHT;
    String CENTER = Constants.CENTER;
    String LEFT = Constants.LEFT;

    pdfStamper.getAcroFields().setField("txtCourse", survey.getCourseCode() + " / " + survey.getCourseName());
    pdfStamper.getAcroFields().setField("txtCollegeName", survey.getCollegeName());

    for (SurveyResponse resp : survey.getSurveyResponses()) {
        sectionNos = sectionNos + resp.getSectionNo() + " ";
        seatsTaken = String.valueOf(resp.getSeatsTaken());
    }

    pdfStamper.getAcroFields().setField("txtSectionNo", sectionNos);
    pdfStamper.getAcroFields().setField("txtDepartmentName", survey.getDepartmentName());
    pdfStamper.getAcroFields().setField("txtEmpName", survey.getEmpName());
    pdfStamper.getAcroFields().setField("txtStudentRegistered", seatsTaken);

    pdfStamper.getAcroFields().setField("txtSemesterYear", semesterYear);

    pdfStamper.getAcroFields().setGenerateAppearances(true);

    /* ****************** */

    PdfPTable table = new PdfPTable(13);

    table.addCell(getPdfCell("", 2, 0, font, LEFT));
    table.addCell(getPdfCell(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.teaching.items", null), 2, 0,
            font, CENTER));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.number", null), 0,
                    6, font, CENTER));
    table.addCell(getPdfCell(
            UtilProperty.getMessage("prop.course.teaching.survey.analysis.response.percentage", null), 2, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.mean", null), 0, 4,
            font, CENTER));

    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree.strong", null), 0,
                    0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.disagree", null), 0,
            0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.agree.strong", null),
            0, 0, font, CENTER));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.applicable.not", null), 0,
                    0, font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.total", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.sect", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.crs", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.dept", null), 0, 0,
            font, CENTER));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.col", null), 0, 0,
            font, CENTER));

    /* ---------------------------------------------------------------------------- */
    table.addCell(getPdfCell("", 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.course.items", null),
            0, 12, font, CENTER));

    int cTotal = 0;
    float cPctVal = 0f;
    float cSectionMean = 0f;
    float cCourseMean = 0f;
    float cDepart = 0f;
    float cCollege = 0f;
    int rowCount = 0;

    for (SurveyResponse sures : survey.getSurveyResponses()) {
        for (Analysis analysis : sures.getAnalysisList()) {
            if (analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14")
                    || analysis.getQuestion().equals(questionByYear)) {
                /***  First part    ***/
                table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font));
                table.addCell(
                        getPdfCell(
                                UtilProperty.getMessage("prop.course.teaching.survey.analysis.set"
                                        + questionSetNo + ".question" + analysis.getQuestionLabel(), null),
                                0, 0, font, LEFT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT));

                cTotal = cTotal + analysis.getTotal();
                cPctVal = cPctVal + analysis.getPercentageResponse();
                cSectionMean = cSectionMean + analysis.getSectionMean();
                cCourseMean = cCourseMean + analysis.getCollegeMean();
                cDepart = cDepart + analysis.getDepartmentMean();
                cCollege = cCollege + analysis.getCollegeMean();
                rowCount = rowCount + 1;

            }
        }
    }

    /***  First part - Summary   ***/
    table.addCell(getPdfCell(String.valueOf(""), 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0,
            0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(""), 0, 5, font));
    table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT));

    table.addCell(getPdfCell("", 0, 13, font));

    table.addCell(getPdfCell("", 0, 0, font));
    table.addCell(
            getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.teaching.items", null), 0,
                    12, font, LEFT));

    cTotal = 0;
    cPctVal = 0f;
    cSectionMean = 0f;
    cCourseMean = 0f;
    cDepart = 0f;
    cCollege = 0f;
    rowCount = 0;
    for (SurveyResponse sures : survey.getSurveyResponses()) {
        for (Analysis analysis : sures.getAnalysisList()) {
            if (!(analysis.getQuestion().equals("Q2") || analysis.getQuestion().equals("Q14")
                    || analysis.getQuestion().equals(questionByYear))) {

                table.addCell(getPdfCell(analysis.getQuestion(), 0, 0, font));
                table.addCell(
                        getPdfCell(
                                UtilProperty.getMessage("prop.course.teaching.survey.analysis.set"
                                        + questionSetNo + ".question" + analysis.getQuestionLabel(), null),
                                0, 0, font, LEFT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongDisagree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDisAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getStrongAgree()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getNotApplicable()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getTotal()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getPercentageResponse()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getSectionMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCourseMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getDepartmentMean()), 0, 0, font, RIGHT));
                table.addCell(getPdfCell(String.valueOf(analysis.getCollegeMean()), 0, 0, font, RIGHT));

                cTotal = cTotal + analysis.getTotal();
                cPctVal = cPctVal + analysis.getPercentageResponse();
                cSectionMean = cSectionMean + analysis.getSectionMean();
                cCourseMean = cCourseMean + analysis.getCollegeMean();
                cDepart = cDepart + analysis.getDepartmentMean();
                cCollege = cCollege + analysis.getCollegeMean();
                rowCount = rowCount + 1;

            }

        }

    }

    /***  Second part - Summary   ***/
    table.addCell(getPdfCell(String.valueOf(""), 0, 0, font));
    table.addCell(getPdfCell(UtilProperty.getMessage("prop.course.teaching.survey.analysis.summary", null), 0,
            0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(""), 0, 5, font));
    table.addCell(getPdfCell(String.valueOf(cTotal), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cPctVal / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cSectionMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCourseMean / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cDepart / rowCount)), 0, 0, font, RIGHT));
    table.addCell(getPdfCell(String.valueOf(formatter.format(cCollege / rowCount)), 0, 0, font, RIGHT));

    if (!survey.getMessage().equals("")) {
        table.addCell(getPdfCell("", 0, 13, font));
        table.addCell(getPdfCell("", 0, 0, font));
        table.addCell(getPdfCell(survey.getMessage(), 0, 12, font, CENTER));
    }

    table.setTotalWidth(750);
    table.setLockedWidth(true);
    table.setWidths(new float[] { 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });

    ColumnText column = new ColumnText(pdfStamper.getOverContent(1));
    Rectangle rectPage1 = new Rectangle(120, 20, 659, 480);

    column.setSimpleColumn(rectPage1);
    column.addElement(table);

    int status = column.go();

    pdfStamper.setFormFlattening(true);

    pdfStamper.close();

    pdfTemplate.close();

    res.setContentType("application/pdf");

    return res.getPortletOutputStream();

}

From source file:org.alfresco.extension.countersign.action.executer.PDFAddSignatureFieldActionExecuter.java

License:Open Source License

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef,
 * org.alfresco.service.cmr.repository.NodeRef)
 *///w  ww . j a  v a 2s  .c om
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {

    NodeService ns = serviceRegistry.getNodeService();
    if (ns.exists(actionedUponNodeRef) == false) {
        // node doesn't exist - can't do anything
        return;
    }

    String fieldName = (String) ruleAction.getParameterValue(PARAM_FIELDNAME);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);

    JSONObject box;
    int page = -1;

    // parse out the position JSON
    JSONObject positionObj = null;

    try {
        positionObj = (JSONObject) parser.parse(position);
    } catch (ParseException e) {
        logger.error("Could not parse position JSON from Share");
        throw new AlfrescoRuntimeException("Could not parse position JSON from Share");
    }

    // get the page
    page = Integer.parseInt(String.valueOf(positionObj.get("page")));

    // get the box
    box = (JSONObject) positionObj.get("box");

    try {
        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());
        OutputStream cos = serviceRegistry.getContentService()
                .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream();

        PdfStamper stamp = new PdfStamper(reader, cos);

        // does a field with this name already exist?
        AcroFields allFields = stamp.getAcroFields();

        // if this doc is already signed, cannot add a new sig field without 
        if (allFields.getSignatureNames() != null && allFields.getSignatureNames().size() > 0) {
            throw new AlfrescoRuntimeException("This document has signatures applied, "
                    + "adding a new signature field would invalidate existing signatures");
        }

        // cant create duplicate field names
        if (allFields.getFieldType(fieldName) == AcroFields.FIELD_TYPE_SIGNATURE) {
            throw new AlfrescoRuntimeException(
                    "A signature field named " + fieldName + " already exists in this document");
        }

        // create the signature field
        Rectangle pageRect = reader.getPageSizeWithRotation(page);
        Rectangle sigRect = positionBlock(pageRect, box);
        PdfFormField sigField = stamp.addSignature(fieldName, page, sigRect.getLeft(), sigRect.getBottom(),
                sigRect.getRight(), sigRect.getTop());

        // style the field (no borders)
        sigField.setBorder(new PdfBorderArray(0, 0, 0));
        sigField.setBorderStyle(new PdfBorderDictionary(0, PdfBorderDictionary.STYLE_SOLID));
        allFields.regenerateField(fieldName);

        // apply the change and close streams
        stamp.close();
        reader.close();
        cos.close();

        // once the signature field has been added, apply the sig field aspect
        if (!ns.hasAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE)) {
            ns.addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNABLE, null);
        }

        // now update the signature fields metadata
        Serializable currentFields = ns.getProperty(actionedUponNodeRef,
                CounterSignSignatureModel.PROP_SIGNATUREFIELDS);
        ArrayList<String> fields = new ArrayList<String>();

        if (currentFields != null) {
            fields.addAll((List<String>) currentFields);
        }

        fields.add(fieldName);
        ns.setProperty(actionedUponNodeRef, CounterSignSignatureModel.PROP_SIGNATUREFIELDS, fields);
    } catch (IOException ioex) {
        throw new AlfrescoRuntimeException(ioex.getMessage());
    } catch (DocumentException dex) {
        throw new AlfrescoRuntimeException(dex.getMessage());
    }
}

From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java

License:Open Source License

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef,
 * org.alfresco.service.cmr.repository.NodeRef)
 *//*w ww  . j  a va2  s  .  c  o m*/
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {

    if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == false) {
        // node doesn't exist - can't do anything
        return;
    }

    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON);
    Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE);
    Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC);

    boolean useSignatureField = false;
    String user = AuthenticationUtil.getRunAsUser();
    String positionType = "predefined";
    String positionLoc = "center";
    JSONObject box;
    int page = -1;

    // parse out the position JSON
    JSONObject positionObj = null;

    try {
        positionObj = (JSONObject) parser.parse(position);
    } catch (ParseException e) {
        logger.error("Could not parse position JSON from Share");
        throw new AlfrescoRuntimeException("Could not parse position JSON from Share");
    }

    // get the page
    page = Integer.parseInt(String.valueOf(positionObj.get("page")));

    // get the positioning type
    positionType = String.valueOf(positionObj.get("type"));

    // get the position (field or predefined)
    positionLoc = String.valueOf(positionObj.get("position"));

    // get the box (if required)
    box = (JSONObject) positionObj.get("box");

    int width = 350;
    int height = 75;

    File tempDir = null;

    // current date, used for both signing the PDF and creating the
    // associated signature object
    Calendar now = Calendar.getInstance();

    try {
        // get the keystore, pk and cert chain
        SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user);
        KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword);
        PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = keystore.getCertificateChain(alias);

        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());
        OutputStream cos = serviceRegistry.getContentService()
                .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream();

        PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true);
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);

        // set reason for signature, location of signer, and date
        sap.setReason(reason);
        sap.setLocation(location);
        sap.setSignDate(now);

        // get the image for the signature
        BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height);
        // save the signature image back to the signatureProvider
        signatureProvider.saveSignatureImage(sigImage, signatureJson);

        if (visible) {
            //if this is a graphic sig, set the graphic here
            if (graphic) {
                sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
                sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE));
            } else {
                sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);
            }

            // either insert the sig at a defined field or at a defined position / drawn loc
            if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) {
                Rectangle pageRect = reader.getPageSizeWithRotation(page);
                sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null);
            } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) {
                Rectangle pageRect = reader.getPageSizeWithRotation(page);
                sap.setVisibleSignature(positionBlock(pageRect, box), page, null);
            } else {
                sap.setVisibleSignature(positionLoc);
                useSignatureField = true;
            }
        }

        // close the stamp, applying the changes to the PDF
        stamp.close();
        reader.close();
        cos.close();

        //delete the temp file
        file.delete();

        // apply the "signed" aspect
        serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED,
                new HashMap<QName, Serializable>());

        // create a "signature" node and associate it with the signed doc
        addSignatureNodeAssociation(actionedUponNodeRef, location, reason,
                useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc);

    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.crossref.pdfmark.Main.java

License:Open Source License

public Main(String[] args) {
    if (args.length == 0) {
        printUsage();//  w  w  w  . j a  v a  2s. c om
        System.exit(2);
    }

    CmdLineParser parser = new CmdLineParser();
    Option provideXmpOp = parser.addStringOption('p', "xmp-file");
    Option overwriteOp = parser.addBooleanOption('f', "force");
    Option outputOp = parser.addStringOption('o', "output-dir");
    Option doiOp = parser.addStringOption('d', "doi");
    Option searchOp = parser.addBooleanOption('s', "search-for-doi");
    Option copyrightOp = parser.addBooleanOption("no-copyright");
    Option rightsOp = parser.addStringOption("rights-agent");
    Option apiKeyOp = parser.addStringOption("api-key");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException e) {
        printUsage();
        System.exit(2);
    }

    String optionalXmpPath = (String) parser.getOptionValue(provideXmpOp, "");
    String outputDir = (String) parser.getOptionValue(outputOp, "");
    String explicitDoi = (String) parser.getOptionValue(doiOp, "");
    boolean useTheForce = (Boolean) parser.getOptionValue(overwriteOp, Boolean.FALSE);
    boolean searchForDoi = (Boolean) parser.getOptionValue(searchOp, Boolean.FALSE);
    boolean noCopyright = (Boolean) parser.getOptionValue(copyrightOp, Boolean.FALSE);
    String rightsAgent = (String) parser.getOptionValue(rightsOp, "");
    String apiKey = (String) parser.getOptionValue(apiKeyOp, ApiKey.DEFAULT);

    if (!explicitDoi.equals("") && searchForDoi) {
        exitWithError(2, "-d and -s are mutually exclusive options.");
    }

    if (!outputDir.isEmpty() && !new File(outputDir).exists()) {
        exitWithError(2, "The output directory, '" + outputDir + "' does not exist.");
    }

    byte[] optionalXmpData = null;

    if (!optionalXmpPath.equals("")) {
        /* We will take XMP data from a file. */
        FileInfo xmpFile = FileInfo.readFileFully(optionalXmpPath);
        if (xmpFile.missing) {
            exitWithError(2, "Error: File '" + xmpFile.path + "' does not exist.");
        } else if (xmpFile.error != null) {
            exitWithError(2, "Error: Could not read '" + xmpFile.path + "' because of:\n" + xmpFile.error);
        }

        optionalXmpData = xmpFile.data;
    }

    grabber = new MetadataGrabber(apiKey);

    /* Now we're ready to merge our imported or generated XMP data with what
     * is already in each PDF. */

    for (String pdfFilePath : parser.getRemainingArgs()) {
        String outputPath = getOutFileName(pdfFilePath);

        /* Grab the leaf. */
        if (outputPath.contains(File.separator)) {
            String[] split = outputPath.split(File.separator);
            outputPath = split[split.length - 1];
        }

        if (!outputDir.isEmpty()) {
            outputPath = outputDir + File.separator + outputPath;
        } else {
            /* Output to the working directory. */
        }

        File pdfFile = new File(pdfFilePath);
        File outputFile = new File(outputPath);

        byte[] resolvedXmpData = null;

        if (!pdfFile.exists()) {
            exitWithError(2, "Error: File '" + pdfFilePath + "' does not exist.");
        }

        if (outputFile.exists() && !useTheForce) {
            exitWithError(2, "Error: File '" + outputPath + "' already exists.\nTry using -f (force).");
        }

        try {
            if (!useTheForce && isLinearizedPdf(new FileInputStream(pdfFile))) {
                exitWithError(2,
                        "Error: '" + pdfFilePath + "' is a" + " linearized PDF and force is not specified."
                                + " This tool will output non-linearized PDF."
                                + "\nIf you don't mind that, use -f (force).");
            }
        } catch (IOException e) {
            exitWithError(2, "Error: Could not determine linearization" + " because of:\n" + e);
        }

        if (!explicitDoi.equals("")) {
            resolvedXmpData = getXmpForDoi(explicitDoi, !noCopyright, rightsAgent);
        }

        try {
            new File(outputFile.getPath() + ".tmp").deleteOnExit();

            FileInputStream fileIn = new FileInputStream(pdfFile);
            FileOutputStream fileOut = new FileOutputStream(outputFile.getPath() + ".tmp");
            PdfReader reader = new PdfReader(fileIn);
            PdfStamper stamper = new PdfStamper(reader, fileOut);

            byte[] merged = reader.getMetadata();

            if (optionalXmpData != null) {
                merged = XmpUtils.mergeXmp(merged, optionalXmpData);
            }

            if (resolvedXmpData != null) {
                merged = XmpUtils.mergeXmp(merged, resolvedXmpData);
            }

            stamper.setXmpMetadata(merged);

            stamper.close();
            reader.close();

            fileIn = new FileInputStream(outputFile.getPath() + ".tmp");
            writeInfoDictionary(fileIn, outputFile.getPath(), merged);
        } catch (IOException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (DocumentException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (XmpException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (COSVisitorException e) {
            exitWithError(2, "Error: Couldn't write document info dictionary" + " because of:\n" + e);
        }
    }

    shutDown();
}