List of usage examples for com.itextpdf.text.pdf PdfStamper close
public void close() throws DocumentException, IOException
From source file:signpdfitext5.SignPdfItext5.java
public static void signPdf() throws IOException, DocumentException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, GeneralSecurityException { //Se agrega bouncyCastle al provider de java, si no se realiza, arroja un error Provider p = new BouncyCastleProvider(); Security.addProvider(p);//from ww w .jav a 2 s. co m //Se instancia un keystore de tipo pkcs12 para leer el contenedor p12 o pfx KeyStore ks = KeyStore.getInstance("pkcs12"); //Se entrega la ruta y la clave del p12 o pfx ks.load(new FileInputStream(fContenedorp12.getAbsolutePath()), Contenedorp12clave.toCharArray()); //Se obtiene el nombre del certificado String alias = (String) ks.aliases().nextElement(); //Se obtiene la llave privada PrivateKey pk = (PrivateKey) ks.getKey(alias, Contenedorp12clave.toCharArray()); //Se obtiene la cadena de certificados en base al nombre del certificado Certificate[] chain = ks.getCertificateChain(alias); //Se indica el origen del pdf a firmar PdfReader reader = new PdfReader(fpdfOrigen.getAbsolutePath()); //Se indica el destino del pdf firmado PdfStamper stamper = PdfStamper.createSignature(reader, new FileOutputStream(fpdfDestino.getAbsolutePath()), '\0'); //Se indican alguno detalles de la forma en que se firmara PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("It's personal."); appearance.setLocation("Foobar"); // Se entrega la llave privada del certificado, el algoritmo de firma y el provider usado (bouncycastle) ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC"); ExternalDigest digest = new BouncyCastleDigest(); //Se genera la firma y se almacena el pdf como se indico en las lineas anteriores MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS); //Se cierran las instancias para liberar espacio stamper.close(); reader.close(); }
From source file:tutorials.encryptpdf.encryptpdf.java
public static void main(String[] args) { try {/* w w w. ja v a2 s . c o m*/ PdfReader reader = new PdfReader("test.pdf"); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("encrypted.pdf")); stamper.setEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_256 | PdfWriter.DO_NOT_ENCRYPT_METADATA); stamper.close(); reader.close(); } catch (IOException | DocumentException ex) { ex.printStackTrace(); } }
From source file:utility.pdfRead.java
public void readPdfFromUrl(String url) throws MalformedURLException, Exception { URL urlnya = new URL(url); String namafile;//from ww w .j ava 2s .c o m Date d = new Date(); // kode String dataAkun = "Surat Keterangan Domisili Usaha dari Kelurahan dan Kecamatan yang masih berlaku atau Fotocopy dilegalisir Kecamatan"; pdfRead myEncryptor = new pdfRead(); String dataAkunEnkripsi = myEncryptor.encrypt(dataAkun); String dataAkunDekripsi = myEncryptor.decrypt( "AYxJhAMLk4fftR5XcqYDoUO4GaMY7sNX19k5SRxWWedGj6RB3tSUUmtdx1KHYf19EE1rLonm/3XikRnNoG/Q0rXkbiXO3QXHnmn2douw6SSwrirgYGoHmR3U4wmGUCxXqAERQFd5rdCZcK0CII7sPsb2uiTYqA97"); System.out.println("Text Asli: " + dataAkun); System.out.println("Text Terenkripsi :" + dataAkunEnkripsi); System.out.println("Text Terdekripsi :" + dataAkunDekripsi); // kode byte[] ba1 = new byte[5 * 1024]; // byte[] ba1 = new byte[10*1024]; int baLength; InputStream is1 = null; ByteArrayOutputStream bios = new ByteArrayOutputStream(); ByteArrayOutputStream biosPlusWatermark = new ByteArrayOutputStream(); ByteArrayOutputStream biosPlusWatermarkQr = new ByteArrayOutputStream(); AMedia amedia = null; try { // report.setSrc(url); // ssl disable // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); URLConnection urlConn = urlnya.openConnection(); try { // Read the PDF from the URL and save to a local file is1 = urlnya.openStream(); while ((baLength = is1.read(ba1)) != -1) { bios.write(ba1, 0, baLength); } } catch (Exception e) { } finally { is1.close(); bios.close(); } // add watermark try { PdfReader reader = new PdfReader(bios.toByteArray()); int n = reader.getNumberOfPages(); // create a stamper that will copy the document to a new file try { // Read the PDF from the URL and save to a local file is1 = urlnya.openStream(); while ((baLength = is1.read(ba1)) != -1) { biosPlusWatermark.write(ba1, 0, baLength); } } catch (Exception e) { } finally { is1.close(); biosPlusWatermark.close(); } PdfStamper stamp = new PdfStamper(reader, biosPlusWatermark, '\0', true); int i = 0; PdfContentByte under; Image img = Image.getInstance("img/watermark.png"); img.setTransparency(new int[] { 0x00, 0x10 }); img.setAbsolutePosition(0, 0); while (i < n) { i++; under = stamp.getOverContent(i); under.addImage(img); } stamp.close(); } catch (Exception e) { System.out.println("err watermark:" + e); amedia = new AMedia("Dokumen", "pdf", "application/pdf", bios.toByteArray()); } // add QRcode try { PdfReader reader = new PdfReader(biosPlusWatermark.toByteArray()); int n = reader.getNumberOfPages(); BarcodeQRCode qrcode = new BarcodeQRCode(dataAkunEnkripsi, 50, 50, null); Image image = qrcode.getImage(); Image mask = qrcode.getImage(); mask.makeMask(); image.setImageMask(mask); // create a stamper that will copy the document to a new file try { // Read the PDF from the URL and save to a local file is1 = urlnya.openStream(); while ((baLength = is1.read(ba1)) != -1) { biosPlusWatermarkQr.write(ba1, 0, baLength); } } catch (Exception e) { } finally { is1.close(); biosPlusWatermarkQr.close(); } PdfStamper stamp = new PdfStamper(reader, biosPlusWatermarkQr, '\0', false); int i = 0; PdfContentByte under; Image img = Image.getInstance(image); img.setTransparency(new int[] { 0x00, 0x10 }); img.setAbsolutePosition(0, 0); while (i < n) { i++; under = stamp.getOverContent(i); under.addImage(img); } stamp.close(); amedia = new AMedia("Dokumen", "pdf", "application/pdf", biosPlusWatermarkQr.toByteArray()); } catch (Exception e) { System.out.println("err qrcode:" + e); amedia = new AMedia("Dokumen", "pdf", "application/pdf", bios.toByteArray()); } report.setContent(amedia); } catch (Exception e) { System.out.println("url tidak dapat diakses"); } }
From source file:valstreamtools.ValStrSplitPage.java
private void createPageNo(String inputFileName, String outputFileName, float pageHeight) throws IOException, DocumentException { PdfReader pdfReader = new PdfReader(inputFileName); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(outputFileName)); int pageCount = pdfReader.getNumberOfPages(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); for (int i = 1; i <= pageCount; i++) { PdfContentByte content = pdfStamper.getOverContent(i); content.beginText();/*from w w w. j a v a 2 s.c o m*/ content.setFontAndSize(bf, 8); content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Page " + i + "/" + pageCount, 5, pageHeight - 15, 0); content.endText(); } pdfStamper.close(); pdfReader.close(); }
From source file:watermarkpdf.FXMLDocumentController.java
@FXML private void handleButtonAction(ActionEvent event) throws DocumentException, IOException { if (tfPhrase.getLength() > 0) { lbl_Result.setText(""); PdfReader reader = new PdfReader(tf_PathFile.getText()); Rectangle mediabox = reader.getPageSize(1); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream( tf_PathFile.getText().substring(0, tf_PathFile.getLength() - 4) + "_out.pdf")); stamper.setRotateContents(false); BaseFont bf = BaseFont.createFont("TNR.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font font = new Font(bf); int iPos = tfPhrase.getText().indexOf('#'); for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte canvas = stamper.getOverContent(i); if (iPos >= 0) { if (cbox_LU.isSelected()) { switch (i) { case 1: ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos - 5) + "? ? " + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); break; case 2: ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos - 5) + " ? " + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); break; default: ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos) + (i - 1) + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); }/*from w w w . ja va 2s .com*/ } else { if (i == 1) ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos - 5) + " ? " + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); else ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase((tfPhrase.getText().substring(0, iPos) + (i) + tfPhrase.getText().substring(iPos + 1)), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); } } else { ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(tfPhrase.getText(), font), mediabox.getRight() / 3, mediabox.getTop() - 40, 0); } ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(tf_append.getText(), font), mediabox.getRight() * 2 / 3, mediabox.getTop() - 20, 0); } stamper.close(); reader.close(); if (tf_PagePrint.getLength() > 0) { reader = new PdfReader( tf_PathFile.getText().substring(0, tf_PathFile.getLength() - 4) + "_out.pdf"); reader.selectPages(tf_PagePrint.getText()); stamper = new PdfStamper(reader, new FileOutputStream( tf_PathFile.getText().substring(0, tf_PathFile.getLength() - 4) + "_out_cut.pdf")); stamper.close(); reader.close(); } lbl_Result.setText(" "); } }