Java Code Examples for com.lowagie.text.pdf.PdfStamper#close()

The following examples show how to use com.lowagie.text.pdf.PdfStamper#close() . 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: 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 2
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 3
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 4
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 5
Source File: AbstractPdfStamperView.java    From java-technology-stack 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 6
Source File: AbstractPdfStamperView.java    From lams with 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 7
Source File: XfdfExampleTest.java    From itext2 with 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 8
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 9
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 10
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 11
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 12
Source File: AddWatermarkPageNumbersTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
    * Reads the pages of an existing PDF file, adds pagenumbers and a watermark.

    */
@Test
   public  void main() throws Exception {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(PdfTestBase.RESOURCES_DIR +"ChapterSection.pdf");
           int n = reader.getNumberOfPages();
           // we create a stamper that will copy the document to a new file
           PdfStamper stamp = new PdfStamper(reader,PdfTestBase.getOutputStream("watermark_pagenumbers.pdf"));
           // adding some metadata
           HashMap<String, String> moreInfo = new HashMap<String, String>();
           moreInfo.put("Author", "Bruno Lowagie");
           stamp.setMoreInfo(moreInfo);
           // adding content to each page
           int i = 0;
           PdfContentByte under;
           PdfContentByte over;
           Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR +"watermark.jpg");
           BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
           img.setAbsolutePosition(200, 400);
           while (i < n) {
           	i++;
           	// watermark under the existing page
           	under = stamp.getUnderContent(i);
           	under.addImage(img);
           	// text over the existing page
           	over = stamp.getOverContent(i);
           	over.beginText();
           	over.setFontAndSize(bf, 18);
           	over.setTextMatrix(30, 30);
           	over.showText("page " + i);
           	over.setFontAndSize(bf, 32);
           	over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
           	over.endText();
           }
           // adding an extra page
           stamp.insertPage(1, PageSize.A4);
           over = stamp.getOverContent(1);
       	over.beginText();
       	over.setFontAndSize(bf, 18);
           over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
           over.endText();
           // adding a page from another document
           PdfReader reader2 = new PdfReader(PdfTestBase.RESOURCES_DIR +"SimpleAnnotations1.pdf");
           under = stamp.getUnderContent(1);
           under.addTemplate(stamp.getImportedPage(reader2, 3), 1, 0, 0, 1, 0, 0);
           // closing PdfStamper will generate the new PDF file
           stamp.close();
   }
 
Example 13
Source File: PdfSurveyServices.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 */
public static Map<String, Object> setAcroFields(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> results = ServiceUtil.returnSuccess();
    Delegator delegator = dctx.getDelegator();
    try {
        Map<String, Object> acroFieldMap = UtilGenerics.checkMap(context.get("acroFieldMap"));
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfStamper s = new PdfStamper(r, baos);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);

        for (String fieldName : map.keySet()) {
            String fieldValue = fs.getField(fieldName);
            Object obj = acroFieldMap.get(fieldName);
            if (obj instanceof Date) {
                Date d=(Date)obj;
                fieldValue=UtilDateTime.toDateString(d);
            } else if (obj instanceof Long) {
                Long lg=(Long)obj;
                fieldValue=lg.toString();
            } else if (obj instanceof Integer) {
                Integer ii=(Integer)obj;
                fieldValue=ii.toString();
            }   else {
                fieldValue=(String)obj;
            }

            if (UtilValidate.isNotEmpty(fieldValue)) {
                fs.setField(fieldName, fieldValue);
            }
        }

        s.close();
        baos.close();
        ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
        results.put("outByteBuffer", outByteBuffer);
    } catch (DocumentException | IOException | GeneralException e) {
        Debug.logError(e, module);
        results = ServiceUtil.returnError(e.getMessage());
    }
    return results;
}
 
Example 14
Source File: CashReceiptCoverSheetServiceImpl.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Use iText <code>{@link PdfStamper}</code> to stamp information from <code>{@link CashReceiptDocument}</code> into field
 * values on a PDF Form Template.
 *
 * @param document The cash receipt document the values will be pulled from.
 * @param searchPath The directory path of the template to be used to generate the cover sheet.
 * @param returnStream The output stream the cover sheet will be written to.
 */
protected void stampPdfFormValues(CashReceiptDocument document, String searchPath, OutputStream returnStream) throws Exception {
    String templateName = CR_COVERSHEET_TEMPLATE_NM;

    try {
        // populate form with document values

        //KFSMI-7303
        //The PDF template is retrieved through web static URL rather than file path, so the File separator is unnecessary
        final boolean isWebResourcePath = StringUtils.containsIgnoreCase(searchPath, "HTTP");

        //skip the File.separator if reference by web resource
        PdfStamper stamper = new PdfStamper(new PdfReader(searchPath + (isWebResourcePath? "" : File.separator) + templateName), returnStream);
        AcroFields populatedCoverSheet = stamper.getAcroFields();

        populatedCoverSheet.setField(DOCUMENT_NUMBER_FIELD, document.getDocumentNumber());
        populatedCoverSheet.setField(INITIATOR_FIELD, document.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId());
        populatedCoverSheet.setField(CREATED_DATE_FIELD, document.getDocumentHeader().getWorkflowDocument().getDateCreated().toString());
        populatedCoverSheet.setField(AMOUNT_FIELD, document.getTotalDollarAmount().toString());
        populatedCoverSheet.setField(ORG_DOC_NUMBER_FIELD, document.getDocumentHeader().getOrganizationDocumentNumber());
        populatedCoverSheet.setField(CAMPUS_FIELD, document.getCampusLocationCode());

        if (document.getDepositDate() != null) {
            // This value won't be set until the CR document is
            // deposited. A CR document is deposited only when it has
            // been associated with a Cash Management Document (CMD)
            // and with a Deposit within that CMD. And only when the
            // CMD is submitted and FINAL, will the CR documents
            // associated with it, be "deposited." So this value will
            // fill in at an arbitrarily later point in time. So your
            // code shouldn't expect it, but if it's there, then
            // display it.
            populatedCoverSheet.setField(DEPOSIT_DATE_FIELD, document.getDepositDate().toString());
        }
        populatedCoverSheet.setField(DESCRIPTION_FIELD, document.getDocumentHeader().getDocumentDescription());
        populatedCoverSheet.setField(EXPLANATION_FIELD, document.getDocumentHeader().getExplanation());

        /*
         * We should print original amounts before cash manager approves the CR; after that, we should print confirmed amounts.
         * Note that, in CashReceiptAction.printCoverSheet, it always retrieves the CR from DB, rather than from the current form.
         * Since during CashManagement route node, the CR can't be saved until CM approves/disapproves the document; this means
         * that if CM prints during this route node, he will get the original amounts. This is consistent with our logic here.
         */
        boolean isConfirmed = document.isConfirmed();
        KualiDecimal totalCheckAmount = !isConfirmed ? document.getTotalCheckAmount() : document.getTotalConfirmedCheckAmount();
        KualiDecimal totalCurrencyAmount = !isConfirmed ? document.getTotalCurrencyAmount() : document.getTotalConfirmedCurrencyAmount();
        KualiDecimal totalCoinAmount = !isConfirmed ? document.getTotalCoinAmount() : document.getTotalConfirmedCoinAmount();
        KualiDecimal totalCashInAmount = !isConfirmed ? document.getTotalCashInAmount() : document.getTotalConfirmedCashInAmount();
        KualiDecimal totalMoneyInAmount = !isConfirmed ? document.getTotalMoneyInAmount() : document.getTotalConfirmedMoneyInAmount();
        KualiDecimal totalChangeCurrencyAmount = !isConfirmed ? document.getTotalChangeCurrencyAmount() : document.getTotalConfirmedChangeCurrencyAmount();
        KualiDecimal totalChangeCoinAmount = !isConfirmed ? document.getTotalChangeCoinAmount() : document.getTotalConfirmedChangeCoinAmount();
        KualiDecimal totalChangeAmount = !isConfirmed ? document.getTotalChangeAmount() : document.getTotalConfirmedChangeAmount();
        KualiDecimal totalNetAmount = !isConfirmed ? document.getTotalNetAmount() : document.getTotalConfirmedNetAmount();

        populatedCoverSheet.setField(CHECKS_FIELD, totalCheckAmount.toString());
        populatedCoverSheet.setField(CURRENCY_FIELD, totalCurrencyAmount.toString());
        populatedCoverSheet.setField(COIN_FIELD, totalCoinAmount.toString());
        populatedCoverSheet.setField(CASH_IN_FIELD, totalCashInAmount.toString());
        populatedCoverSheet.setField(MONEY_IN_FIELD, totalMoneyInAmount.toString());
        populatedCoverSheet.setField(CHANGE_CURRENCY_FIELD, totalChangeCurrencyAmount.toString());
        populatedCoverSheet.setField(CHANGE_COIN_FIELD, totalChangeCoinAmount.toString());
        populatedCoverSheet.setField(CHANGE_OUT_FIELD, totalChangeAmount.toString());
        populatedCoverSheet.setField(RECONCILIATION_TOTAL_FIELD, totalNetAmount.toString());

        stamper.setFormFlattening(true);
        stamper.close();
    }
    catch (Exception e) {
        LOG.error("Error creating coversheet for: " + document.getDocumentNumber() + ". ::" + e);
        throw e;
    }
}