Java 类com.lowagie.text.pdf.PdfReader 实例源码

项目:itext2    文件:PdfContentStreamProcessor.java   
public static byte[] getContentBytesFromPdfObject(PdfObject object) throws IOException {
    switch (object.type()) {
    case PdfObject.INDIRECT:
        return getContentBytesFromPdfObject(PdfReader.getPdfObject(object));
    case PdfObject.STREAM:
        return PdfReader.getStreamBytes((PRStream) PdfReader.getPdfObject(object));
    case PdfObject.ARRAY:
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ListIterator<PdfObject> iter = ((PdfArray) object).listIterator();
        while (iter.hasNext()) {
            PdfObject element = iter.next();
            baos.write(getContentBytesFromPdfObject(element));
        }
        return baos.toByteArray();
    default:
        throw new IllegalStateException("Unsupported type: " + object.getClass().getCanonicalName());
    }
}
项目:itext2    文件:XfdfExampleTest.java   
/**
 * Merges an XFDF file with a PDF form.
 */
@Test
public void main() throws Exception {

    // merging the FDF file
    PdfReader pdfreader = new PdfReader(PdfTestBase.RESOURCES_DIR + "SimpleRegistrationForm.pdf");
    PdfStamper stamp = new PdfStamper(pdfreader, PdfTestBase.getOutputStream("registered_xfdf.pdf"));
    XfdfReader fdfreader = new XfdfReader(PdfTestBase.RESOURCES_DIR + "register.xfdf");
    AcroFields form = stamp.getAcroFields();
    form.setFields(fdfreader);
    stamp.close();

}
项目:itext2    文件:Image.java   
/**
 * Reuses an existing image.
 * @param ref the reference to the image dictionary
 * @throws BadElementException on error
 * @return the image
 */    
public static Image getInstance(PRIndirectReference ref) throws BadElementException {
    PdfDictionary dic = (PdfDictionary)PdfReader.getPdfObjectRelease(ref);
    int width = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.WIDTH))).intValue();
    int height = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.HEIGHT))).intValue();
    Image imask = null;
    PdfObject obj = dic.get(PdfName.SMASK);
    if (obj != null && obj.isIndirect()) {
        imask = getInstance((PRIndirectReference)obj);
    }
    else {
        obj = dic.get(PdfName.MASK);
        if (obj != null && obj.isIndirect()) {
            PdfObject obj2 = PdfReader.getPdfObjectRelease(obj);
            if (obj2 instanceof PdfDictionary)
                imask = getInstance((PRIndirectReference)obj);
        }
    }
    Image img = new ImgRaw(width, height, 1, 1, null);
    img.imageMask = imask;
    img.directReference = ref;
    return img;
}
项目:helium    文件:SignaturaPluginTest.java   
@SuppressWarnings("unchecked")
private List<DadesCertificat> obtenirDadesCertificatPdf(
        byte[] signatura) throws Exception {
    PdfReader reader = new PdfReader(new ByteArrayInputStream(signatura));
    AcroFields af = reader.getAcroFields();
    ArrayList<String> names = af.getSignatureNames();
    for (String name: names) {
        PdfPKCS7 pk = af.verifySignature(name);
        Certificate pkc[] = pk.getCertificates();
        List<DadesCertificat> dadesCertificats = new ArrayList<DadesCertificat>();
        for (Certificate cert: pkc) {
            if (cert instanceof X509Certificate) {
                int basicConstraints = ((X509Certificate)cert).getBasicConstraints();
                // Només afegeix els certificats que no son de CA
                if (basicConstraints == -1)
                    dadesCertificats.add(getDadesCertificat((X509Certificate)cert));
            }
        }
        return dadesCertificats;
    }
    return null;
}
项目:sistra    文件:UtilPDF.java   
/**
 * 
 * @param pdfOut
 * @param pdfIn
 * @param pagesToDelete
 * @throws Exception
 */
public static void extractPages(OutputStream pdfOut,InputStream pdfIn, int[] pages) throws Exception{

    if (pages.length <= 0) {
           throw new Exception("Debe eliminar al menos una p�gina");
       }

    List pagesToKeep = new ArrayList();
    for (int i=0;i<pages.length;i++){
        pagesToKeep.add(new Integer(pages[i]));
    }


       PdfCopyFields  writer = new PdfCopyFields(pdfOut);
       int permission=0;

       PdfReader reader = new PdfReader(pdfIn);
       permission = reader.getPermissions();
       if (permission != 0){
        writer.setEncryption(null, null,permission, PdfWriter.STRENGTH40BITS);
       }
    writer.addDocument(reader,pagesToKeep);

       writer.close();

    }
项目:OSCAR-ConCert    文件:AddEditDocumentAction.java   
public static int countNumOfPages(String fileName) {// count number of pages in a local pdf file

        int numOfPage = 0;
        String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
                if (!docdownload.endsWith(File.separator))
                {
                    docdownload += File.separator; 
                }
        String filePath = docdownload + fileName;

        try {
            PdfReader reader = new PdfReader(filePath);
            numOfPage = reader.getNumberOfPages();
            reader.close();

        } catch (IOException e) {
            MiscUtils.getLogger().error("Error", e);
        }
        return numOfPage;
    }
项目:OSCAR-ConCert    文件:DocumentUploadAction.java   
/**
 * Counts the number of pages in a local pdf file.
 * @param fileName the name of the file
 * @return the number of pages in the file
 */
public int countNumOfPages(String fileName) {// count number of pages in a
                                                // local pdf file
    int numOfPage = 0;
    String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    String filePath = docdownload + fileName;

    try {
        PdfReader reader = new PdfReader(filePath);
        numOfPage = reader.getNumberOfPages();
        reader.close();
    } catch (IOException e) {
        logger.debug(e.toString());
    }
    return numOfPage;
}
项目:Lucee4    文件:PDFUtil.java   
public static void encrypt(PDFDocument doc, OutputStream os, String newUserPassword, String newOwnerPassword, int permissions, int encryption) throws ApplicationException, DocumentException, IOException {
    byte[] user = newUserPassword==null?null:newUserPassword.getBytes();
    byte[] owner = newOwnerPassword==null?null:newOwnerPassword.getBytes();

    PdfReader pr = doc.getPdfReader();
    List bookmarks = SimpleBookmark.getBookmark(pr);
    int n = pr.getNumberOfPages();

    Document document = new Document(pr.getPageSizeWithRotation(1));
    PdfCopy writer = new PdfCopy(document, os);
    if(encryption!=ENCRYPT_NONE)writer.setEncryption(user, owner, permissions, encryption);
    document.open();


    PdfImportedPage page;
    for (int i = 1; i <= n; i++) {
        page = writer.getImportedPage(pr, i);
        writer.addPage(page);
    }
    PRAcroForm form = pr.getAcroForm();
    if (form != null)writer.copyAcroForm(pr);
    if (bookmarks!=null)writer.setOutlines(bookmarks);
    document.close();
}
项目:Lucee4    文件:PDFUtil.java   
public static PdfReader toPdfReader(PageContext pc,Object value, String password) throws IOException, PageException {
    if(value instanceof PdfReader) return (PdfReader) value;
    if(value instanceof PDFDocument) return ((PDFDocument) value).getPdfReader();
    if(Decision.isBinary(value)){
        if(password!=null)return new PdfReader(Caster.toBinary(value),password.getBytes());
        return new PdfReader(Caster.toBinary(value));
    }
    if(value instanceof Resource) {
        if(password!=null)return new PdfReader(IOUtil.toBytes((Resource)value),password.getBytes());
        return new PdfReader(IOUtil.toBytes((Resource)value));
    }
    if(value instanceof String) {
        if(password!=null)return new PdfReader(IOUtil.toBytes(Caster.toResource(pc,value,true)),password.getBytes());
        return new PdfReader(IOUtil.toBytes((Resource)value));
    }
    throw new CasterException(value,PdfReader.class);
}
项目:kansalaisaloite    文件:SupportStatementPdf.java   
public static void modifyPdf(InputStream pdfTemplate, OutputStream modifiedPdf, String name, LocalDate startDate) throws IOException, DocumentException {
        // NOTE: Can we use this?
//        PdfReader.unethicalreading = true;

        PdfReader reader = new PdfReader(pdfTemplate);
        PdfStamper stamper = new PdfStamper(reader, modifiedPdf);

        fill(stamper.getAcroFields(), name, startDate);

        stamper.setFormFlattening(true);
        stamper.partialFormFlattening(INITIATIVE_NAME);
        stamper.partialFormFlattening(INITIATIVE_DAY);
        stamper.partialFormFlattening(INITIATIVE_MONTH);
        stamper.partialFormFlattening(INITIATIVE_YEAR);

        stamper.close();
        reader.close();
    }
项目:openeos    文件:OsgiTestCase.java   
@Test
public void testAutoRegisterJasperReportsExecuteReport() throws Exception {
    JasperReport report1 = (JasperReport) JRLoader.loadObject(getClass().getClassLoader().getResource(TEST_REPORT_1));

    Hashtable<String, Object> properties = new Hashtable<String, Object>();
    properties.put(Constants.SERVICE_RANKING, 0);
    properties.put(org.openeos.reporting.jasperreports.Constants.SERVICE_REPORT_ID, TEST_REPORT_1);
    ServiceRegistration<JasperReport> register1 = bc.registerService(JasperReport.class, report1, properties);

    HashMap<String, Object> parameters = new HashMap<String, Object>();
    parameters.put(JRParameter.REPORT_DATA_SOURCE, new JRBeanCollectionDataSource(createSampleBeans()));
    InputStream result = reportingService.generateReport(TEST_REPORT_1, "application/pdf", parameters);
    PdfReader reader = new PdfReader(result);
    assertEquals(1, reader.getNumberOfPages());
    reader.close();
    register1.unregister();
}
项目:openeos    文件:OsgiTestCase.java   
@Test
public void testEntityReportingService() throws Exception {
    JasperReport report = (JasperReport) JRLoader.loadObject(getClass().getClassLoader().getResource(TEST_REPORT_BEAN));

    Hashtable<String, Object> properties = new Hashtable<String, Object>();
    properties.put(Constants.SERVICE_RANKING, 0);
    properties.put(org.openeos.reporting.jasperreports.Constants.SERVICE_REPORT_ID, TEST_REPORT_ID);
    ServiceRegistration<JasperReport> register1 = bc.registerService(JasperReport.class, report, properties);

    InputStream result = entityReportingService.generateReport(TEST_REPORT_ID, BusinessPartner.class, bpDAO.findAll());

    PdfReader reader = new PdfReader(result);
    assertEquals(1, reader.getNumberOfPages());

    assertTrue(findPdfString(reader, "testField"));

    reader.close();
    register1.unregister();

}
项目:openeos    文件:OsgiTestCase.java   
private void testReport(String reportName) throws Exception {
    JasperReport report = (JasperReport) JRLoader.loadObject(getClass().getClassLoader().getResource(reportName));

    Hashtable<String, Object> properties = new Hashtable<String, Object>();
    properties.put(Constants.SERVICE_RANKING, 0);
    properties.put(org.openeos.reporting.jasperreports.Constants.SERVICE_REPORT_ID, TEST_REPORT_ID);
    ServiceRegistration<JasperReport> register1 = bc.registerService(JasperReport.class, report, properties);

    HashMap<String, Object> parameters = new HashMap<String, Object>();
    parameters.put(org.openeos.reporting.jasperreports.entity.Constants.PARAMETER_IS_ENTITY_REPORT, true);
    parameters.put(org.openeos.reporting.jasperreports.entity.Constants.PARAMETER_ENTITY_COLLECTION, bpDAO.findAll());
    parameters.put(org.openeos.reporting.jasperreports.entity.Constants.PARAMETER_ENTITY_CLASS, BusinessPartner.class);
    InputStream result = reportingService.generateReport(TEST_REPORT_ID, "application/pdf", parameters);

    PdfReader reader = new PdfReader(result);
    assertEquals(1, reader.getNumberOfPages());

    assertTrue(findPdfString(reader, "testField"));

    reader.close();
    register1.unregister();

}
项目:OLE-INST    文件:CashReceiptCoverSheetServiceImpl.java   
/**
 * Generate a cover sheet for the <code>{@link CashReceiptDocument}</code>. An <code>{@link OutputStream}</code> is written
 * to for the cover sheet.
 * 
 * @param document The cash receipt document the cover sheet is for.
 * @param searchPath The directory path to the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 * @exception DocumentException Thrown if the document provided is invalid, including null.
 * @exception IOException Thrown if there is a problem writing to the output stream.
 * @see org.kuali.rice.kns.module.financial.service.CashReceiptCoverSheetServiceImpl#generateCoverSheet(
 *      org.kuali.module.financial.documentCashReceiptDocument )
 */
public void generateCoverSheet(CashReceiptDocument document, String searchPath, OutputStream returnStream) throws Exception {

    if (isCoverSheetPrintingAllowed(document)) {
        ByteArrayOutputStream stamperStream = new ByteArrayOutputStream();

        stampPdfFormValues(document, searchPath, stamperStream);

        PdfReader reader = new PdfReader(stamperStream.toByteArray());
        Document pdfDoc = new Document(reader.getPageSize(FRONT_PAGE));
        PdfWriter writer = PdfWriter.getInstance(pdfDoc, returnStream);

        pdfDoc.open();
        populateCheckDetail(document, writer, reader);
        pdfDoc.close();
        writer.close();
    }
}
项目:OLE-INST    文件:CashReceiptCoverSheetServiceImpl.java   
/**
 * Method responsible for producing Check Detail section of the cover sheet. Not all Cash Receipt documents have checks.
 * 
 * @param crDoc The CashReceipt document the cover sheet is being created for.
 * @param writer The output writer used to write the check data to the PDF file.
 * @param reader The input reader used to read data from the PDF file.
 */
protected void populateCheckDetail(CashReceiptDocument crDoc, PdfWriter writer, PdfReader reader) throws Exception {
    PdfContentByte content;
    ModifiableInteger pageNumber;
    int checkCount = 0;
    int maxCheckCount = MAX_CHECKS_FIRST_PAGE;

    pageNumber = new ModifiableInteger(0);
    content = startNewPage(writer, reader, pageNumber);

    for (Check current : crDoc.getChecks()) {
        writeCheckNumber(content, current);
        writeCheckDate(content, current);
        writeCheckDescription(content, current);
        writeCheckAmount(content, current);
        setCurrentRenderingYPosition(getCurrentRenderingYPosition() - CHECK_FIELD_HEIGHT);

        checkCount++;

        if (checkCount > maxCheckCount) {
            checkCount = 0;
            maxCheckCount = MAX_CHECKS_NORMAL;
            content = startNewPage(writer, reader, pageNumber);
        }
    }
}
项目:kfs    文件:ContractsGrantsInvoiceReportServiceImpl.java   
/**
 *
 * @param template the path to the original form
 * @param list the replacement list
 * @return
 * @throws IOException
 * @throws DocumentException
 */
protected byte[] renameFieldsIn(String template, Map<String, String> list) throws IOException, DocumentException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // Create the stamper
    PdfStamper stamper = new PdfStamper(new PdfReader(template), baos);
    // Get the fields
    AcroFields fields = stamper.getAcroFields();
    // Loop over the fields
    for (String field : list.keySet()) {
        fields.setField(field, list.get(field));
    }
    // close the stamper
    stamper.close();
    return baos.toByteArray();
}
项目:kfs    文件:CashReceiptCoverSheetServiceImpl.java   
/**
 * Generate a cover sheet for the <code>{@link CashReceiptDocument}</code>. An <code>{@link OutputStream}</code> is written
 * to for the cover sheet.
 *
 * @param document The cash receipt document the cover sheet is for.
 * @param searchPath The directory path to the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 * @exception DocumentException Thrown if the document provided is invalid, including null.
 * @exception IOException Thrown if there is a problem writing to the output stream.
 * @see org.kuali.rice.kns.module.financial.service.CashReceiptCoverSheetServiceImpl#generateCoverSheet(
 *      org.kuali.module.financial.documentCashReceiptDocument )
 */
@Override
public void generateCoverSheet(CashReceiptDocument document, String searchPath, OutputStream returnStream) throws Exception {

    if (isCoverSheetPrintingAllowed(document)) {
        ByteArrayOutputStream stamperStream = new ByteArrayOutputStream();

        stampPdfFormValues(document, searchPath, stamperStream);

        PdfReader reader = new PdfReader(stamperStream.toByteArray());
        Document pdfDoc = new Document(reader.getPageSize(FRONT_PAGE));
        PdfWriter writer = PdfWriter.getInstance(pdfDoc, returnStream);

        pdfDoc.open();
        populateCheckDetail(document, writer, reader);
        pdfDoc.close();
        writer.close();
    }
}
项目:kfs    文件:CashReceiptCoverSheetServiceImpl.java   
/**
 * Method responsible for producing Check Detail section of the cover sheet. Not all Cash Receipt documents have checks.
 *
 * @param crDoc The CashReceipt document the cover sheet is being created for.
 * @param writer The output writer used to write the check data to the PDF file.
 * @param reader The input reader used to read data from the PDF file.
 */
protected void populateCheckDetail(CashReceiptDocument crDoc, PdfWriter writer, PdfReader reader) throws Exception {
    PdfContentByte content;
    ModifiableInteger pageNumber;
    int checkCount = 0;
    int maxCheckCount = MAX_CHECKS_FIRST_PAGE;

    pageNumber = new ModifiableInteger(0);
    content = startNewPage(writer, reader, pageNumber);

    for (Check current : crDoc.getChecks()) {
        writeCheckNumber(content, current);
        writeCheckDate(content, current);
        writeCheckDescription(content, current);
        writeCheckAmount(content, current);
        setCurrentRenderingYPosition(getCurrentRenderingYPosition() - CHECK_FIELD_HEIGHT);

        checkCount++;

        if (checkCount > maxCheckCount) {
            checkCount = 0;
            maxCheckCount = MAX_CHECKS_NORMAL;
            content = startNewPage(writer, reader, pageNumber);
        }
    }
}
项目:studeasy    文件:PdfGenerator.java   
/**
 * Genera il pdf per la richiesta della tesi
 *
 * @param tesiView Vista con il form per raccogliere i dati
 * @param path     Path del file di destinazione
 * @throws IOException
 * @throws DocumentException
 */
public void generatePdfTesi(FormTesi tesiView, String path) throws IOException, DocumentException {

    // Lettura del template
    PdfReader pdfTemplate = new PdfReader(template);
    // Apertura del file di destinazione
    FileOutputStream fileOutputStream = createOutputStream(path);
    // Popolazione del template con i dati
    PdfStamper stamper = new PdfStamper(pdfTemplate, fileOutputStream);

    stamper.setFormFlattening(true);

    stamper.getAcroFields().setField("nome", tesiView.getNome().getText());
    stamper.getAcroFields().setField("cognome", tesiView.getCognome().getText());
    stamper.getAcroFields().setField("matricola", tesiView.getMatricola().getText());
    stamper.getAcroFields().setField("dataNascita", tesiView.getDataNascita().getText());
    stamper.getAcroFields().setField("luogoNascita", tesiView.getLuogoNascita().getText());
    stamper.getAcroFields().setField("eMail", tesiView.getEmail().getText());
    stamper.getAcroFields().setField("annoCorso", tesiView.getAnnoCorso().getText());
    stamper.getAcroFields().setField("professoreRelatore", tesiView.getProfRelatore().getText());
    stamper.getAcroFields().setField("titoloTesi", tesiView.getTitoloTesi().getText());

    pdfTemplate.close();
    stamper.close();
    fileOutputStream.close();
}
项目:PDFTestForAndroid    文件:ConcatenateForms.java   
/**
     * Concatenates 2 PDF files with forms. The resulting PDF has 1 merged
     * AcroForm.
     * 
     * @param args
     *            no arguments needed
     */
    public static void main(String[] args) {
        try {
            //Can't use filename directly
//          PdfReader reader1 = new PdfReader("SimpleRegistrationForm.pdf");
//          PdfReader reader2 = new PdfReader("TextFields.pdf");
            PdfReader reader1 = new PdfReader(PdfTestRunner.getActivity().getResources().openRawResource(R.raw.simpleregistrationform));
            PdfReader reader2 = new PdfReader(PdfTestRunner.getActivity().getResources().openRawResource(R.raw.textfields));
            PdfCopyFields copy = new PdfCopyFields(new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "concatenatedforms.pdf"));
            copy.addDocument(reader1);
            copy.addDocument(reader2);
            copy.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
项目:PDFTestForAndroid    文件:XfdfExample.java   
/**
 * Merges an XFDF file with a PDF form.
 * 
 * @param args
 *            no arguments needed
 */
public static void main(String[] args) {
    try {
        // merging the FDF file
        PdfReader pdfreader = new PdfReader(PdfTestRunner.getActivity().getResources().openRawResource(R.raw.simpleregistrationform));
        String path = android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "registered_xfdf.pdf";
           PdfStamper stamp = new PdfStamper(pdfreader, new FileOutputStream(path));
           InputStream inputStream = PdfTestRunner.getActivity().getResources().openRawResource(R.raw.register);
           byte[] buffer = new byte[inputStream.available()];
           inputStream.read(buffer);
        XfdfReader fdfreader = new XfdfReader(buffer);
        AcroFields form = stamp.getAcroFields();
        form.setFields(fdfreader);
        stamp.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}
项目:zugferd    文件:PdfInvoiceReader.java   
public PdfAttachment unpackFile(PdfDictionary filespec) throws IOException {
    if (filespec == null)
        return null;
    PdfName type = filespec.getAsName(PdfName.TYPE);
    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type))
        return null;
    PdfDictionary ef = filespec.getAsDict(PdfName.EF);
    if (ef == null)
        return null;
    PRStream prs = (PRStream)PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null)
        return null;
    PdfString pdfDesc = filespec.getAsString(PdfName.DESC);
    String desc = pdfDesc != null ? pdfDesc.toString() : "";
    PdfString pdfName = filespec.getAsString(PdfName.F);
    String name = pdfName != null ? pdfName.toString() : "";
    byte[] data = PdfReader.getStreamBytes(prs);
    return new PdfAttachment(name, desc, data);
}
项目:oscar-old    文件:ManageDocumentAction.java   
public ActionForward getDocPageNumber(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

        String doc_no = request.getParameter("doc_no");
        Document d = documentDAO.getDocument(doc_no);
        String filePath = EDocUtil.getDocumentPath(d.getDocfilename());

        int numOfPage = 0;
        try {
            PdfReader reader = new PdfReader(filePath);
            numOfPage = reader.getNumberOfPages();

            HashMap hm = new HashMap();
            hm.put("numOfPage", numOfPage);
            JSONObject jsonObject = JSONObject.fromObject(hm);
            response.getOutputStream().write(jsonObject.toString().getBytes());
        } catch (IOException e) {
            MiscUtils.getLogger().error("Error", e);
        }

        return null;// execute2(mapping, form, request, response);
    }
项目:oscar-old    文件:AddEditDocumentAction.java   
public int countNumOfPages(String fileName) {// count number of pages in a local pdf file

        int numOfPage = 0;
//      String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
//      String filePath = docdownload + fileName;
        String filePath=EDocUtil.getDocumentPath(fileName);

        try {
            PdfReader reader = new PdfReader(filePath);
            numOfPage = reader.getNumberOfPages();
            reader.close();

        } catch (IOException e) {
            MiscUtils.getLogger().error("Error", e);
        }
        return numOfPage;
    }
项目:oscar-old    文件:DocumentUploadAction.java   
/**
     * Counts the number of pages in a local pdf file.
     * @param fileName the name of the file
     * @return the number of pages in the file
     */
    public int countNumOfPages(String fileName) {// count number of pages in a
                                                    // local pdf file
        int numOfPage = 0;
//      String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
//      String filePath = docdownload + fileName;
        String filePath = EDocUtil.getDocumentPath(fileName);

        try {
            PdfReader reader = new PdfReader(filePath);
            numOfPage = reader.getNumberOfPages();
            reader.close();
        } catch (IOException e) {
            logger.debug(e.toString());
        }
        return numOfPage;
    }
项目:DroidText    文件:Image.java   
/**
 * Reuses an existing image.
 * @param ref the reference to the image dictionary
 * @throws BadElementException on error
 * @return the image
 */    
public static Image getInstance(PRIndirectReference ref) throws BadElementException {
    PdfDictionary dic = (PdfDictionary)PdfReader.getPdfObjectRelease(ref);
    int width = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.WIDTH))).intValue();
    int height = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.HEIGHT))).intValue();
    Image imask = null;
    PdfObject obj = dic.get(PdfName.SMASK);
    if (obj != null && obj.isIndirect()) {
        imask = getInstance((PRIndirectReference)obj);
    }
    else {
        obj = dic.get(PdfName.MASK);
        if (obj != null && obj.isIndirect()) {
            PdfObject obj2 = PdfReader.getPdfObjectRelease(obj);
            if (obj2 instanceof PdfDictionary)
                imask = getInstance((PRIndirectReference)obj);
        }
    }
    Image img = new ImgRaw(width, height, 1, 1, null);
    img.imageMask = imask;
    img.directReference = ref;
    return img;
}
项目:DroidText    文件:EncryptPdf.java   
/**
 * Encrypts a PDF document.
 * 
 * @param args
 *            input_file output_file user_password owner_password
 *            permissions 128|40 [new info string pairs]
 */
public static void main(String args[]) {
    System.out.println("PDF document encryptor");
    if (args.length <= STRENGTH || args[PERMISSIONS].length() != 8) {
        usage();
        return;
    }
    try {
        int permissions = 0;
        String p = args[PERMISSIONS];
        for (int k = 0; k < p.length(); ++k) {
            permissions |= (p.charAt(k) == '0' ? 0 : permit[k]);
        }
        System.out.println("Reading " + args[INPUT_FILE]);
        PdfReader reader = new PdfReader(args[INPUT_FILE]);
        System.out.println("Writing " + args[OUTPUT_FILE]);
        HashMap moreInfo = new HashMap();
        for (int k = MOREINFO; k < args.length - 1; k += 2)
            moreInfo.put(args[k], args[k + 1]);
        PdfEncryptor.encrypt(reader, new FileOutputStream(args[OUTPUT_FILE]), args[USER_PASSWORD].getBytes(),
                args[OWNER_PASSWORD].getBytes(), permissions, args[STRENGTH].equals("128"), moreInfo);
        System.out.println("Done.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:wichtel    文件:HelperPdf.java   
/**
 * Returns the text of a given PDF as {@link String}.
 * 
 * @param file
 *           input as PDF
 * @return text of the given PDF
 * @throws IOException
 * @see File
 * @since 0.0.1
 */
public static String getText(final File file) throws IOException { // $JUnit$
    if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(file));
    if (null == file) {
        throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$
    }

    final PdfReader pdfReader = new PdfReader(file.getAbsolutePath());
    final PdfTextExtractor pdfExtractor = new PdfTextExtractor(pdfReader);

    final StringBuilder sb = new StringBuilder();

    for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) {
        sb.append(pdfExtractor.getTextFromPage(page));
        sb.append(HelperString.NEW_LINE);
    }
    final String result = sb.toString();

    if (log.isDebugEnabled()) log.debug(HelperLog.methodExit(result));
    return result;
}
项目:itext2    文件:PdfContentReaderTool.java   
/**
 * Writes information about a specific page from PdfReader to the specified output stream.
 * @since 2.1.5
 * @param reader    the PdfReader to read the page content from
 * @param pageNum   the page number to read
 * @param out       the output stream to send the content to
 * @throws IOException
 */
static public void listContentStreamForPage(PdfReader reader, int pageNum, PrintWriter out) throws IOException {
    out.println("==============Page " + pageNum + "====================");
    out.println("- - - - - Dictionary - - - - - -");
    PdfDictionary pageDictionary = reader.getPageN(pageNum);
    out.println(getDictionaryDetail(pageDictionary));
    out.println("- - - - - Content Stream - - - - - -");
    RandomAccessFileOrArray f = reader.getSafeFile();

    byte[] contentBytes = reader.getPageContent(pageNum, f);
    f.close();


    InputStream is = new ByteArrayInputStream(contentBytes);
    int ch;
    while ((ch = is.read()) != -1){
        out.print((char)ch);
    }

    out.println("- - - - - Text Extraction - - - - - -");
    PdfTextExtractor extractor = new PdfTextExtractor(reader);
    String extractedText = extractor.getTextFromPage(pageNum);
    if (extractedText.length() != 0)
        out.println(extractedText);
    else
        out.println("No text found on page " + pageNum);

    out.println();

}
项目:itext2    文件:PdfContentReaderTool.java   
/**
 * Writes information about each page in a PDF file to the specified output stream.
 * @since 2.1.5
 * @param pdfFile   a File instance referring to a PDF file
 * @param out       the output stream to send the content to
 * @throws IOException
 */
static public void listContentStream(File pdfFile, PrintWriter out) throws IOException {
    PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());

    int maxPageNum = reader.getNumberOfPages();

    for (int pageNum = 1; pageNum <= maxPageNum; pageNum++){
        listContentStreamForPage(reader, pageNum, out);
    }       

}
项目:itext2    文件:EncryptPdf.java   
/**
 * Encrypts a PDF document.
 * 
 * @param args input_file output_file user_password owner_password permissions 128|40 [new info string pairs]
 */
public static void main (String args[]) {
    System.out.println("PDF document encryptor");
    if (args.length <= STRENGTH || args[PERMISSIONS].length() != 8) {
        usage();
        return;
    }
    try {
        int permissions = 0;
        String p = args[PERMISSIONS];
        for (int k = 0; k < p.length(); ++k) {
            permissions |= (p.charAt(k) == '0' ? 0 : permit[k]);
        }
        System.out.println("Reading " + args[INPUT_FILE]);
        PdfReader reader = new PdfReader(args[INPUT_FILE]);
        System.out.println("Writing " + args[OUTPUT_FILE]);
        HashMap moreInfo = new HashMap();
        for (int k = MOREINFO; k < args.length - 1; k += 2)
            moreInfo.put(args[k], args[k + 1]);
        PdfEncryptor.encrypt(reader, new FileOutputStream(args[OUTPUT_FILE]),
            args[USER_PASSWORD].getBytes(), args[OWNER_PASSWORD].getBytes(), permissions, args[STRENGTH].equals("128"), moreInfo);
        System.out.println("Done.");
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
项目:itext2    文件:ConcatenateFormsTest.java   
/**
 * Concatenates 2 PDF files with forms. The resulting PDF has 1 merged AcroForm.
 */
@Test
public void main() throws Exception{
        PdfReader reader1 = new PdfReader(PdfTestBase.RESOURCES_DIR + "SimpleRegistrationForm.pdf");
        PdfReader reader2 = new PdfReader(PdfTestBase.RESOURCES_DIR + "TextFields.pdf");
        PdfCopyFields copy = new PdfCopyFields(PdfTestBase.getOutputStream("concatenatedforms.pdf"));
        copy.addDocument(reader1);
        copy.addDocument(reader2);
        copy.close();
}
项目:itext2    文件:EncryptorExampleTest.java   
/**
 * Reads and encrypts an existing PDF file.
 */
@Test
public void main() throws Exception {
    PdfReader reader = new PdfReader(PdfTestBase.RESOURCES_DIR + "ChapterSection.pdf");
    PdfEncryptor.encrypt(reader, PdfTestBase.getOutputStream("encrypted.pdf"), "Hello".getBytes(),
            "World".getBytes(), PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY, false);
}
项目:itext2    文件:InfoTest.java   
/**
 * Getting information from a PDF file
 * @param args  the names of paths to PDF files.
 */
public void main(String... args) throws Exception {
    BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.getOutputFile("info.txt")));
       for (int i = 0; i < args.length; i++) { 
        PdfReader r = new PdfReader(args[i]);
           out.write(args[i]);
           out.write("\r\n------------------------------------\r\n");
        out.write(r.getInfo().toString());
        out.write("\r\n------------------------------------\r\n");
       }
       out.flush();
       out.close();
}
项目:itext2    文件:ReadEncryptedTest.java   
/**
 * Reads an encrypted PDF document.
 * 
 */
@Test
public void main() throws Exception {
    BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR + "info_encrypted.txt"));
    PdfReader r = new PdfReader(PdfTestBase.RESOURCES_DIR + "HelloEncrypted.pdf", "Hello".getBytes());
    out.write(r.getInfo().toString());
    out.write("\r\n");
    int permissions = r.getPermissions();
    out.write("Printing allowed: " + ((PdfWriter.ALLOW_PRINTING & permissions) > 0));
    out.write("\r\n");
    out.write("Modifying contents allowed: " + ((PdfWriter.ALLOW_MODIFY_CONTENTS & permissions) > 0));
    out.write("\r\n");
    out.write("Copying allowed: " + ((PdfWriter.ALLOW_COPY & permissions) > 0));
    out.write("\r\n");
    out.write("Modifying annotations allowed: " + ((PdfWriter.ALLOW_MODIFY_ANNOTATIONS & permissions) > 0));
    out.write("\r\n");
    out.write("Fill in allowed: " + ((PdfWriter.ALLOW_FILL_IN & permissions) > 0));
    out.write("\r\n");
    out.write("Screen Readers allowed: " + ((PdfWriter.ALLOW_SCREENREADERS & permissions) > 0));
    out.write("\r\n");
    out.write("Assembly allowed: " + ((PdfWriter.ALLOW_ASSEMBLY & permissions) > 0));
    out.write("\r\n");
    out.write("Degraded printing allowed: " + ((PdfWriter.ALLOW_DEGRADED_PRINTING & permissions) > 0));
    out.write("\r\n");
    out.flush();
    out.close();
}
项目:itext2    文件:PdfContentStreamProcessorTest.java   
private void processBytes(final byte[] pdfBytes, final int pageNumber) throws IOException {
    final PdfReader pdfReader = new PdfReader(pdfBytes);

    final PdfDictionary pageDictionary = pdfReader.getPageN(pageNumber);

    final PdfDictionary resourceDictionary = pageDictionary.getAsDict(PdfName.RESOURCES);

    final PdfObject contentObject = pageDictionary.get(PdfName.CONTENTS);
    final byte[] contentBytes = readContentBytes(contentObject);
    _processor.processContent(contentBytes, resourceDictionary);
}
项目:itext2    文件:PdfContentStreamProcessorTest.java   
private byte[] readContentBytes(final PdfObject contentObject) throws IOException {
    final byte[] result;
    switch (contentObject.type()) {
    case PdfObject.INDIRECT:
        final PRIndirectReference ref = (PRIndirectReference) contentObject;
        final PdfObject directObject = PdfReader.getPdfObject(ref);
        result = readContentBytes(directObject);
        break;
    case PdfObject.STREAM:
        final PRStream stream = (PRStream) PdfReader.getPdfObject(contentObject);
        result = PdfReader.getStreamBytes(stream);
        break;
    case PdfObject.ARRAY:
        // Stitch together all content before calling processContent(),
        // because
        // processContent() resets state.
        final ByteArrayOutputStream allBytes = new ByteArrayOutputStream();
        final PdfArray contentArray = (PdfArray) contentObject;
        final ListIterator<?> iter = contentArray.listIterator();
        while (iter.hasNext()) {
            final PdfObject element = (PdfObject) iter.next();
            allBytes.write(readContentBytes(element));
        }
        result = allBytes.toByteArray();
        break;
    default:
        final String msg = "Unable to handle Content of type " + contentObject.getClass();
        throw new IllegalStateException(msg);
    }
    return result;
}
项目:sistra    文件:UtilPDF.java   
/**
 * Concatena varios pdfs
 * @param pdfOut Outputstream al pdf de salida
 * @param pdfIn InputStreams de los pdfs a concatenar
 */
public static void concatenarPdf(OutputStream pdfOut,InputStream [] pdfIn) throws Exception{
    if (pdfIn.length < 2) {
           throw new Exception("Debe concatenar al menos 2 PDFs");
       }

    // Realizamos copia PDFs        
       int f = 0;

       PdfCopyFields  writer = new PdfCopyFields(pdfOut);
       int permission=0;
       while (f < pdfIn.length) {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(pdfIn[f]);            
           // Establecemos permisos del primer documento
           if (f==0){
            permission = reader.getPermissions();
            if (permission != 0){
                writer.setEncryption(null, null,permission, PdfWriter.STRENGTH40BITS);
            }
           }

           writer.addDocument(reader);

           f++;
       }

       writer.close();

    }