com.lowagie.text.pdf.PdfReader Java Examples

The following examples show how to use com.lowagie.text.pdf.PdfReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CashReceiptCoverSheetServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #2
Source File: CashReceiptCoverSheetServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #3
Source File: ITextPDFSignatureService.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public DSSDocument addNewSignatureField(DSSDocument document, SignatureFieldParameters parameters, String pwd) {

	checkDocumentPermissions(document, pwd);
	
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream is = document.openStream();
			PdfReader reader = new PdfReader(is, getPasswordBinary(pwd))) {

		PdfStamper stp = new PdfStamper(reader, baos, '\0', true);

		stp.addSignature(parameters.getName(), parameters.getPage() + 1, parameters.getOriginX(),
				parameters.getOriginY(), parameters.getWidth(), parameters.getHeight());

		stp.close();

		DSSDocument signature = new InMemoryDocument(baos.toByteArray());
		signature.setMimeType(MimeType.PDF);
		return signature;
	} catch (IOException e) {
		throw new DSSException("Unable to add a signature field", e);
	}
}
 
Example #4
Source File: Prd5873Test.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void runTest(MasterReport report)
        throws ResourceException, ReportProcessingException, IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PdfReportUtil.createPDF(report, bout);

    PdfReader reader = new PdfReader(bout.toByteArray());

    printPdfPage(reader);

    final PdfDictionary pageN = reader.getPageN(1);
    final PdfDictionary asDict = pageN.getAsDict(PdfName.RESOURCES);
    final byte[] pageContent = reader.getPageContent(1);
    PdfValidator pv = new PdfValidator();
    pv.processContent(pageContent, asDict);

}
 
Example #5
Source File: Image.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: PdfContentStreamProcessor.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
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());
	}
}
 
Example #7
Source File: FdfExampleTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Writes an FDF file and merges it with a PDF form.
 */
@Test
public void main() throws Exception {

	// writing the FDF file
	FdfWriter fdf = new FdfWriter();
	fdf.setFieldAsString("name", "Bruno Lowagie");
	fdf.setFieldAsString("address", "Baeyensstraat 121, Sint-Amandsberg");
	fdf.setFieldAsString("postal_code", "BE-9040");
	fdf.setFieldAsString("email", "[email protected]");
	fdf.setFile(PdfTestBase.RESOURCES_DIR + "SimpleRegistrationForm.pdf");
	fdf.writeTo(PdfTestBase.getOutputStream("SimpleRegistrationForm.fdf"));

	// merging the FDF file
	PdfReader pdfreader = new PdfReader(PdfTestBase.RESOURCES_DIR + "SimpleRegistrationForm.pdf");
	PdfStamper stamp = new PdfStamper(pdfreader, PdfTestBase.getOutputStream("registered_fdf.pdf"));
	FdfReader fdfreader = new FdfReader(PdfTestBase.OUTPUT_DIR + "SimpleRegistrationForm.fdf");
	AcroFields form = stamp.getAcroFields();
	form.setFields(fdfreader);
	stamp.close();

}
 
Example #8
Source File: Image.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source File: ItextPDFWatermarkWriter.java    From website with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void writeWatermark(String inputFile, String outputFile, Watermark watermark, PageLayout layout) throws Exception {
	try {
		logger.debug("Writing watermark on " + inputFile);
		document = new PdfReader(inputFile);
		try {
			stamper = new PdfStamper(document, new FileOutputStream(outputFile));
			setPageLayout(layout);
			internalWriteWatermark(watermark);
			stamper.close();
		} catch (Exception e) {
			throw new IOException("Unable to write watermark", e);
		}
	} finally {
		if (document != null) {
			document.close();
		}
		if (isEncrypt()) {
			//PdfEncryptor.encrypt(outputFile);
		}
	}
}
 
Example #10
Source File: PAdESLevelBCertificationTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void onDocumentSigned(byte[] byteArray) {
	super.onDocumentSigned(byteArray);

	try (PdfReader reader = new PdfReader(byteArray)) {
		assertEquals(CertificationPermission.MINIMAL_CHANGES_PERMITTED.getCode(), reader.getCertificationLevel());
	} catch (IOException e) {
		throw new DSSException(e);
	}
}
 
Example #11
Source File: CashReceiptCoverSheetServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Responsible for creating a new PDF page and workspace through <code>{@link PdfContentByte}</code> for direct writing to the
 * PDF.
 *
 * @param writer The PDF writer used to write to the new page with.
 * @param reader The PDF reader used to read information from the PDF file.
 * @param pageNumber The current number of pages in the PDF file, which will be incremented by one inside this method.
 *
 * @return The PDFContentByte used to access the new PDF page.
 * @exception DocumentException
 * @exception IOException
 */
protected PdfContentByte startNewPage(PdfWriter writer, PdfReader reader, ModifiableInteger pageNumber) throws DocumentException, IOException {
    PdfContentByte retval;
    PdfContentByte under;
    Rectangle pageSize;
    Document pdfDoc;
    PdfImportedPage newPage;

    pageNumber.increment();
    pageSize = reader.getPageSize(FRONT_PAGE);
    retval = writer.getDirectContent();
    // under = writer.getDirectContentUnder();

    if (pageNumber.getInt() > FRONT_PAGE) {
        newPage = writer.getImportedPage(reader, CHECK_PAGE_NORMAL);
        setCurrentRenderingYPosition(pageSize.top(TOP_MARGIN + CHECK_DETAIL_HEADING_HEIGHT));
    }
    else {
        newPage = writer.getImportedPage(reader, FRONT_PAGE);
        setCurrentRenderingYPosition(pageSize.top(TOP_FIRST_PAGE));
    }

    pdfDoc = retval.getPdfDocument();
    pdfDoc.newPage();
    retval.addTemplate(newPage, 0, 0);
    retval.setFontAndSize(getTextFont(), 8);

    return retval;
}
 
Example #12
Source File: DunningLetterServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generates the pdf file for printing the invoices.
 *
 * @param list
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
protected void generateCombinedPdfForInvoices(Collection<ContractsGrantsInvoiceDocument> list, byte[] report, OutputStream outputStream) throws DocumentException, IOException {
    PdfCopyFields copy = new PdfCopyFields(outputStream);
    copy.open();
    copy.addDocument(new PdfReader(report));
    for (ContractsGrantsInvoiceDocument invoice : list) {
        for (InvoiceAddressDetail invoiceAddressDetail : invoice.getInvoiceAddressDetails()) {
            Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());
            if (ObjectUtils.isNotNull(note) && note.getAttachment().getAttachmentFileSize() > 0) {
                copy.addDocument(new PdfReader(note.getAttachment().getAttachmentContents()));
            }
        }
    }
    copy.close();
}
 
Example #13
Source File: DunningLetterServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Loops through the collection of lookup results, creating pdfs for each and appending the bytes of the pdfs onto the returned "finalReport"
 * @see org.kuali.kfs.module.ar.document.service.DunningLetterDistributionService#createDunningLettersForAllResults(org.kuali.kfs.module.ar.businessobject.DunningLetterTemplate, java.util.Collection)
 */
@Override
public byte[] createDunningLettersForAllResults(Collection<GenerateDunningLettersLookupResult> results) throws DocumentException, IOException {
    ByteArrayOutputStream zos = null;
    PdfCopyFields reportCopy = null;
    byte[] finalReport = null;
    try {
        zos = new ByteArrayOutputStream();
        reportCopy = new PdfCopyFields(zos);
        reportCopy.open();
        List<DunningLetterTemplate> dunningLetterTemplates = (List<DunningLetterTemplate>) getBusinessObjectService().findAll(DunningLetterTemplate.class);
        for (DunningLetterTemplate dunningLetterTemplate : dunningLetterTemplates) {
            for (GenerateDunningLettersLookupResult generateDunningLettersLookupResult : results) {
                final byte[] report = createDunningLetters(dunningLetterTemplate, generateDunningLettersLookupResult);
                if (ObjectUtils.isNotNull(report)) {
                    reportCopy.addDocument(new PdfReader(report));
                }
            }
        }
        reportCopy.close();
        finalReport = zos.toByteArray();
    } finally {
        if (zos != null) {
            zos.close();
        }
    }
    return finalReport;
}
 
Example #14
Source File: ContractsGrantsInvoiceReportServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generates the pdf file for printing the invoices.
 *
 * @param list
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
protected void generateCombinedPdfForInvoices(Collection<ContractsGrantsInvoiceDocument> list, OutputStream outputStream) throws DocumentException, IOException {
    PdfCopyFields copy = new PdfCopyFields(outputStream);
    boolean pageAdded = false;
    for (ContractsGrantsInvoiceDocument invoice : list) {
        // add a document
        List<InvoiceAddressDetail> invoiceAddressDetails = invoice.getInvoiceAddressDetails();

        for (InvoiceAddressDetail invoiceAddressDetail : invoiceAddressDetails) {
            if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {
                Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());
                Integer numberOfCopiesToPrint = invoiceAddressDetail.getCustomerAddress().getCustomerCopiesToPrint();
                if (ObjectUtils.isNull(numberOfCopiesToPrint)) {
                    numberOfCopiesToPrint = 1;
                }

                if (!ObjectUtils.isNull(note)) {
                    for (int i = 0; i < numberOfCopiesToPrint; i++) {
                        if (!pageAdded) {
                            copy.open();
                        }
                        pageAdded = true;
                        copy.addDocument(new PdfReader(note.getAttachment().getAttachmentContents()));
                    }
                }
                invoiceAddressDetail.setInitialTransmissionDate(new Date(new java.util.Date().getTime()));
            }
        }
        documentService.updateDocument(invoice);
    }
    if (pageAdded) {
        copy.close();
    }
}
 
Example #15
Source File: ContractsGrantsInvoiceReportServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 * @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();
}
 
Example #16
Source File: ITextPDFSignatureService.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean containsFilledSignature(PdfReader reader) {
	AcroFields acroFields = reader.getAcroFields();
	List<String> signatureNames = acroFields.getSignedFieldNames();
	for (String name : signatureNames) {
		PdfDict dictionary = new ITextPdfDict(acroFields.getSignatureDictionary(name));
		PdfSigDictWrapper signatureDictionary = new PdfSigDictWrapper(dictionary);
		if (Utils.isArrayNotEmpty(signatureDictionary.getContents())) {
			return true;
		}
	}
	return false;
}
 
Example #17
Source File: DSS1444Test.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void test3() throws IOException {
	try (InputStream is = getClass().getResourceAsStream("/small-red.jpg")) {
		Exception exception = assertThrows(IOException.class, () -> new PdfReader(is));
		assertEquals("PDF header signature not found.", exception.getMessage());
	}
}
 
Example #18
Source File: PdfEncryptionValidateIT.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testSaveEncrypted() throws Exception {
  final URL url = getClass().getResource( "pdf-encryption-validate.xml" );
  assertNotNull( url );
  final ResourceManager resourceManager = new ResourceManager();
  resourceManager.registerDefaults();
  final Resource directly = resourceManager.createDirectly( url, MasterReport.class );
  final MasterReport report = (MasterReport) directly.getResource();

  final byte[] b = createPDF( report );
  final PdfReader reader = new PdfReader( b, DocWriter.getISOBytes( "Duck" ) );
  assertTrue( reader.isEncrypted() );
}
 
Example #19
Source File: DSS1444Test.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void test() throws IOException {
	try (InputStream is = getClass().getResourceAsStream("/EmptyPage-corrupted.pdf")) {
		assertThrows(NullPointerException.class, () -> new PdfReader(is));
	}

}
 
Example #20
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
public String cropPdf(String pdfFilePath) throws DocumentException, IOException, Exception {
	String filename = FilenameUtils.getBaseName(pdfFilePath) + "_cropped." + FilenameUtils.getExtension(pdfFilePath);
	filename = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename);
	PdfReader reader = new PdfReader(pdfFilePath);
	try {
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(filename));
		try {
			for (int i = 1; i <= reader.getNumberOfPages(); i++) {
				PdfDictionary pdfDictionary = reader.getPageN(i);
				PdfArray cropArray = new PdfArray();
				Rectangle box = getSmallestBox(reader, i);
				//Rectangle cropbox = reader.getCropBox(i);
				if (box != null) {
					cropArray.add(new PdfNumber(box.getLeft()));
					cropArray.add(new PdfNumber(box.getBottom()));
					cropArray.add(new PdfNumber(box.getLeft() + box.getWidth()));
					cropArray.add(new PdfNumber(box.getBottom() + box.getHeight()));
					pdfDictionary.put(PdfName.CROPBOX, cropArray);
					pdfDictionary.put(PdfName.MEDIABOX, cropArray);
					pdfDictionary.put(PdfName.TRIMBOX, cropArray);
					pdfDictionary.put(PdfName.BLEEDBOX, cropArray);
				}
			}
			return filename;
		} finally {
			stamper.close();
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw e;
	} finally {
		reader.close();
	}
}
 
Example #21
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
private Rectangle getSmallestBox(PdfReader reader, int pageNumber) {
	Map<Float, Rectangle> boxAreas = new TreeMap<Float, Rectangle>();
	
	Rectangle cropBox = reader.getBoxSize(pageNumber, "crop");
	Rectangle trimBox = reader.getBoxSize(pageNumber, "trim");
	Rectangle artBox = reader.getBoxSize(pageNumber, "art");
	Rectangle bleedBox = reader.getBoxSize(pageNumber, "bleed");
	
	if (cropBox != null) {
		boxAreas.put(getBoxArea(cropBox), cropBox);
	}
	if (trimBox != null) {
		boxAreas.put(getBoxArea(trimBox), trimBox);
	}
	if (artBox != null) {
		boxAreas.put(getBoxArea(artBox), artBox);
	}
	if (bleedBox != null) {
		boxAreas.put(getBoxArea(bleedBox), bleedBox);
	}
	Rectangle result = null;
	for (Float area : boxAreas.keySet()) {
		result = boxAreas.get(area);
		break;
	}
	return result;
}
 
Example #22
Source File: ITextPDFSignatureService.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private PdfObject getPdfObjectForToken(Token token, Map<String, Long> knownObjects, PdfReader reader, PdfWriter writer)
		throws IOException {
	String digest = getTokenDigest(token);
	Long objectNumber = knownObjects.get(digest);
	if (objectNumber == null) {
		PdfStream ps = new PdfStream(token.getEncoded());
		return writer.addToBody(ps, false).getIndirectReference();
	} else {
		return new PRIndirectReference(reader, objectNumber.intValue());
	}
}
 
Example #23
Source File: DSS1444Test.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void test4() throws IOException {
	try (InputStream is = getClass().getResourceAsStream("/sample.pdf")) {
		PdfReader pdfReader = new PdfReader(is);
		assertNotNull(pdfReader);
	}
}
 
Example #24
Source File: ITextPDFSignatureService.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private PdfDictionary findExistingSignature(PdfReader reader, String signatureFieldId) {
	AcroFields acroFields = reader.getAcroFields();
	List<String> signatureNames = acroFields.getFieldNamesWithBlankSignatures();
	if (signatureNames.contains(signatureFieldId)) {
		Item item = acroFields.getFieldItem(signatureFieldId);
		return item.getMerged(0);
	}
	throw new DSSException("The signature field '" + signatureFieldId + "' does not exist.");
}
 
Example #25
Source File: ITextDocumentReader.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * The OpenPDF implementation of the Reader
 * 
 * @param binaries a byte array of a PDF to read
 * @param passwordProtection binaries of a password to open a protected document
 * @throws IOException if an exception occurs
 * @throws eu.europa.esig.dss.pades.exception.InvalidPasswordException if the password is not provided or invalid for a protected document
 */
public ITextDocumentReader(byte[] binaries, byte[] passwordProtection) throws IOException, InvalidPasswordException {
	Objects.requireNonNull(binaries, "The document binaries must be defined!");
	try {
		this.pdfReader = new PdfReader(binaries, passwordProtection);
	} catch (BadPasswordException e) {
           throw new InvalidPasswordException(e.getMessage());
	}
}
 
Example #26
Source File: ITextDocumentReader.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * The OpenPDF implementation of the Reader
 * 
 * @param dssDocument {@link DSSDocument} to read
 * @param passwordProtection binaries of a password to open a protected document
 * @throws IOException if an exception occurs
 * @throws InvalidPasswordException if the password is not provided or invalid for a protected document
 */
public ITextDocumentReader(DSSDocument dssDocument, byte[] passwordProtection) throws IOException, InvalidPasswordException {
	Objects.requireNonNull(dssDocument, "The document must be defined!");
	try (InputStream is = dssDocument.openStream()) {
		this.pdfReader = new PdfReader(is, passwordProtection);
	} catch (BadPasswordException e) {
           throw new InvalidPasswordException(e.getMessage());
	}
}
 
Example #27
Source File: PdfWatermarkUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
	FontFactory.register("fonts/fireflysung.ttf"); // fonts/fireflysung.ttf in fireflysung.jar
	Font font = FontFactory.getFont("fonts/fireflysung.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
	PdfReader pdfReader = new PdfReader("/tmp/ex/test.pdf");
	PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("/tmp/ex/test-out.pdf"));
	addWatermark(pdfStamper, font.getBaseFont(), Color.RED, "測試");
	pdfStamper.close();
}
 
Example #28
Source File: AbstractPdfStamperView.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected final void renderMergedOutputModel(
		Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

	// IE workaround: write into byte array first.
	ByteArrayOutputStream baos = createTemporaryOutputStream();

	PdfReader reader = readPdfResource();
	PdfStamper stamper = new PdfStamper(reader, baos);
	mergePdfDocument(model, stamper, request, response);
	stamper.close();

	// Flush to HTTP response.
	writeToResponse(response, baos);
}
 
Example #29
Source File: AbstractPdfStamperView.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected final void renderMergedOutputModel(
		Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

	// IE workaround: write into byte array first.
	ByteArrayOutputStream baos = createTemporaryOutputStream();

	PdfReader reader = readPdfResource();
	PdfStamper stamper = new PdfStamper(reader, baos);
	mergePdfDocument(model, stamper, request, response);
	stamper.close();

	// Flush to HTTP response.
	writeToResponse(response, baos);
}
 
Example #30
Source File: PdfSurveyServices.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 */
public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> acroFieldMap = new HashMap<>();
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Delegator delegator = dctx.getDelegator();
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        PdfStamper s = new PdfStamper(r,os);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);

        for (String fieldName : map.keySet()) {
            String parmValue = fs.getField(fieldName);
            acroFieldMap.put(fieldName, parmValue);
        }

    } catch (DocumentException | GeneralException | IOException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("acroFieldMap", acroFieldMap);
return results;
}