Java Code Examples for com.lowagie.text.pdf.PdfReader

The following examples show how to use com.lowagie.text.pdf.PdfReader. These examples are extracted from open source projects. 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 Project: gcs   Author: richardwilkes   File: Image.java    License: 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 #2
Source Project: itext2   Author: albfernandez   File: Image.java    License: 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 #3
Source Project: itext2   Author: albfernandez   File: PdfContentStreamProcessor.java    License: 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 #4
Source Project: itext2   Author: albfernandez   File: FdfExampleTest.java    License: 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 #5
Source Project: dss   Author: esig   File: ITextPDFSignatureService.java    License: 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 #6
Source Project: website   Author: Paperight   File: ItextPDFWatermarkWriter.java    License: 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 #7
Source Project: kfs   Author: kuali   File: CashReceiptCoverSheetServiceImpl.java    License: 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 #8
Source Project: kfs   Author: kuali   File: CashReceiptCoverSheetServiceImpl.java    License: 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 #9
Source Project: pentaho-reporting   Author: pentaho   File: Prd5873Test.java    License: 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 #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractPdfStamperView.java    License: 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 #11
Source Project: java-technology-stack   Author: codeEngraver   File: AbstractPdfStamperView.java    License: 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 #12
Source Project: lams   Author: lamsfoundation   File: AbstractPdfStamperView.java    License: GNU General Public License v2.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 #13
Source Project: gcs   Author: richardwilkes   File: PdfContentReaderTool.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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();

}
 
Example #14
Source Project: gcs   Author: richardwilkes   File: PdfContentReaderTool.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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);
	}

}
 
Example #15
Source Project: itext2   Author: albfernandez   File: PdfContentReaderTool.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
    
}
 
Example #16
Source Project: itext2   Author: albfernandez   File: PdfContentReaderTool.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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);
    }       
        
}
 
Example #17
Source Project: itext2   Author: albfernandez   File: EncryptPdf.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example #18
Source Project: itext2   Author: albfernandez   File: ConcatenateFormsTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #19
Source Project: itext2   Author: albfernandez   File: EncryptorExampleTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #20
Source Project: itext2   Author: albfernandez   File: InfoTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #21
Source Project: itext2   Author: albfernandez   File: ReadEncryptedTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #22
Source Project: itext2   Author: albfernandez   File: XfdfExampleTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();

}
 
Example #23
Source Project: itext2   Author: albfernandez   File: PdfContentStreamProcessorTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #24
Source Project: itext2   Author: albfernandez   File: PdfContentStreamProcessorTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #25
Source Project: scipio-erp   Author: ilscipio   File: PdfSurveyServices.java    License: 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;
}
 
Example #26
Source Project: spring4-understanding   Author: langtianya   File: AbstractPdfStamperView.java    License: 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 #27
Source Project: bamboobsc   Author: billchen198318   File: PdfWatermarkUtils.java    License: 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 Project: dss   Author: esig   File: ITextDocumentReader.java    License: 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 #29
Source Project: dss   Author: esig   File: ITextDocumentReader.java    License: 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 #30
Source Project: dss   Author: esig   File: ITextPDFSignatureService.java    License: 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.");
}