List of usage examples for org.apache.pdfbox.pdmodel.graphics.image PDImageXObject createFromFile
public static PDImageXObject createFromFile(String imagePath, PDDocument doc) throws IOException
From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox2.PADESPDFBOXSigner.java
License:EUPL
public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature, PDFASSignatureInterface genericSigner) throws PdfAsException { //String fisTmpFile = null; PDFAsVisualSignatureProperties properties = null; if (!(genericPdfObject instanceof PDFBOXObject)) { // tODO://from w w w .ja va 2s .c om throw new PdfAsException(); } PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject; if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) { // tODO: throw new PdfAsException(); } PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner; String pdfaVersion = null; PDDocument doc = null; SignatureOptions options = new SignatureOptions(); COSDocument visualSignatureDocumentGuard = null; try { doc = pdfObject.getDocument(); SignaturePlaceholderData signaturePlaceholderData = PlaceholderFilter .checkPlaceholderSignature(pdfObject.getStatus(), pdfObject.getStatus().getSettings()); TablePos tablePos = null; if (signaturePlaceholderData != null) { // Placeholder found! logger.info("Placeholder data found."); if (signaturePlaceholderData.getProfile() != null) { logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile()); requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile()); } tablePos = signaturePlaceholderData.getTablePos(); if (tablePos != null) { SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); float minWidth = signatureProfileConfiguration.getMinWidth(); if (minWidth > 0) { if (tablePos.getWidth() < minWidth) { tablePos.width = minWidth; logger.debug("Correcting placeholder with to minimum width {}", minWidth); } } logger.debug("Placeholder Position set to: " + tablePos.toString()); } } PDSignature signature = new PDSignature(); signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); // default // filter signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter())); SignatureProfileSettings signatureProfileSettings = TableFactory .createProfile(requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings()); /* * Check if input document is PDF-A conform * if (signatureProfileSettings.isPDFA()) { // TODO: run preflight parser runPDFAPreflight(pdfObject.getOriginalDocument()); } */ ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus()); String signerName = resolver.resolve("SIG_SUBJECT", signatureProfileSettings.getValue("SIG_SUBJECT"), signatureProfileSettings); signature.setName(signerName); // take signing time from provided signer... signature.setSignDate(signer.getSigningDate()); // ...and update operation status in order to use exactly this date for the complete signing process requestedSignature.getStatus().setSigningDate(signer.getSigningDate()); String signerReason = signatureProfileSettings.getSigningReason(); if (signerReason == null) { signerReason = "PAdES Signature"; } signature.setReason(signerReason); logger.debug("Signing reason: " + signerReason); logger.debug("Signing @ " + signer.getSigningDate().getTime().toString()); // the signing date, needed for valid signature // signature.setSignDate(signer.getSigningDate()); signer.setPDSignature(signature); int signatureSize = 0x1000; try { String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE); if (reservedSignatureSizeString != null) { signatureSize = Integer.parseInt(reservedSignatureSizeString); } logger.debug("Reserving {} bytes for signature", signatureSize); } catch (NumberFormatException e) { logger.warn("Invalid configuration value: {} should be a number using 0x1000", SIG_RESERVED_SIZE); } options.setPreferredSignatureSize(signatureSize); if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) { pdfaVersion = getPDFAVersion(doc); signatureProfileSettings.setPDFAVersion(pdfaVersion); } // Is visible Signature if (requestedSignature.isVisual()) { logger.debug("Creating visual signature block"); SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); if (tablePos == null) { // ================================================================ // PositioningStage (visual) -> find position or use // fixed // position String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition(); TablePos signaturePos = null; String signaturePosString = signatureProfileConfiguration.getDefaultPositioning(); if (signaturePosString != null) { logger.debug("using signature Positioning: " + signaturePos); signaturePos = new TablePos(signaturePosString); } logger.debug("using Positioning: " + posString); if (posString != null) { // Merge Signature Position tablePos = new TablePos(posString, signaturePos); } else { // Fallback to signature Position! tablePos = signaturePos; } if (tablePos == null) { // Last Fallback default position tablePos = new TablePos(); } } //Legacy Modes not supported with pdfbox2 anymore // boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning(); // boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning(); // create Table describtion Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(), requestedSignature); IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings()); IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main); /* * PDDocument originalDocument = PDDocument .load(new * ByteArrayInputStream(pdfObject.getStatus() * .getPdfObject().getOriginalDocument())); */ PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos, "", doc, visualObject, pdfObject.getStatus().getSettings()); logger.debug("Positioning: {}", positioningInstruction.toString()); if (positioningInstruction.isMakeNewPage()) { int last = doc.getNumberOfPages() - 1; PDDocumentCatalog root = doc.getDocumentCatalog(); PDPage lastPage = root.getPages().get(last); root.getPages().getCOSObject().setNeedToBeUpdated(true); PDPage p = new PDPage(lastPage.getMediaBox()); p.setResources(new PDResources()); p.setRotation(lastPage.getRotation()); doc.addPage(p); } // handle rotated page int targetPageNumber = positioningInstruction.getPage(); logger.debug("Target Page: " + targetPageNumber); PDPage targetPage = doc.getPages().get(targetPageNumber - 1); int rot = targetPage.getRotation(); logger.debug("Page rotation: " + rot); // positioningInstruction.setRotation(positioningInstruction.getRotation() // + rot); logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation()); SignaturePositionImpl position = new SignaturePositionImpl(); position.setX(positioningInstruction.getX()); position.setY(positioningInstruction.getY()); position.setPage(positioningInstruction.getPage()); position.setHeight(visualObject.getHeight()); position.setWidth(visualObject.getWidth()); requestedSignature.setSignaturePosition(position); properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings); properties.buildSignature(); /* * ByteArrayOutputStream sigbos = new * ByteArrayOutputStream(); * sigbos.write(StreamUtils.inputStreamToByteArray * (properties .getVisibleSignature())); sigbos.close(); */ if (signaturePlaceholderData != null) { // Placeholder found! // replace placeholder URL fileUrl = PADESPDFBOXSigner.class.getResource("/placeholder/empty.jpg"); PDImageXObject img = PDImageXObject.createFromFile(fileUrl.getPath(), doc); img.getCOSObject().setNeedToBeUpdated(true); // PDDocumentCatalog root = doc.getDocumentCatalog(); // PDPageNode rootPages = root.getPages(); // List<PDPage> kids = new ArrayList<PDPage>(); // rootPages.getAllKids(kids); int pageNumber = positioningInstruction.getPage(); PDPage page = doc.getPages().get(pageNumber - 1); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); COSDictionary xobjectsDictionary = (COSDictionary) page.getResources().getCOSObject() .getDictionaryObject(COSName.XOBJECT); xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img); xobjectsDictionary.setNeedToBeUpdated(true); page.getResources().getCOSObject().setNeedToBeUpdated(true); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); } if (signatureProfileSettings.isPDFA() || signatureProfileSettings.isPDFA3()) { PDDocumentCatalog root = doc.getDocumentCatalog(); COSBase base = root.getCOSObject().getItem(COSName.OUTPUT_INTENTS); if (base == null) { InputStream colorProfile = null; try { colorProfile = PDDocumentCatalog.class .getResourceAsStream("/icm/sRGB Color Space Profile.icm"); try { PDOutputIntent oi = new PDOutputIntent(doc, colorProfile); oi.setInfo("sRGB IEC61966-2.1"); oi.setOutputCondition("sRGB IEC61966-2.1"); oi.setOutputConditionIdentifier("sRGB IEC61966-2.1"); oi.setRegistryName("http://www.color.org"); root.addOutputIntent(oi); root.getCOSObject().setNeedToBeUpdated(true); logger.info("added Output Intent"); } catch (Throwable e) { e.printStackTrace(); throw new PdfAsException("Failed to add Output Intent", e); } } finally { IOUtils.closeQuietly(colorProfile); } } } options.setPage(positioningInstruction.getPage()); options.setVisualSignature(properties.getVisibleSignature()); } visualSignatureDocumentGuard = options.getVisualSignature(); doc.addSignature(signature, signer, options); String sigFieldName = signatureProfileSettings.getSignFieldValue(); if (sigFieldName == null) { sigFieldName = "PDF-AS Signatur"; } int count = PdfBoxUtils.countSignatures(doc, sigFieldName); sigFieldName = sigFieldName + count; PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm(); // PDStructureTreeRoot pdstRoot = // doc.getDocumentCatalog().getStructureTreeRoot(); // COSDictionary dic = // doc.getDocumentCatalog().getCOSDictionary(); // PDStructureElement el = new PDStructureElement("Widget", // pdstRoot); PDSignatureField signatureField = null; if (acroFormm != null) { @SuppressWarnings("unchecked") List<PDField> fields = acroFormm.getFields(); if (fields != null) { for (PDField pdField : fields) { if (pdField != null) { if (pdField instanceof PDSignatureField) { PDSignatureField tmpSigField = (PDSignatureField) pdField; if (tmpSigField.getSignature() != null && tmpSigField.getSignature().getCOSObject() != null) { if (tmpSigField.getSignature().getCOSObject() .equals(signature.getCOSObject())) { signatureField = (PDSignatureField) pdField; } } } } } } else { logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]"); } if (signatureField != null) { signatureField.setPartialName(sigFieldName); } if (properties != null) { signatureField.setAlternateFieldName(properties.getAlternativeTableCaption()); } else { signatureField.setAlternateFieldName(sigFieldName); } } else { logger.warn("Failed to name Signature Field! [Cannot find acroForm!]"); } // PDF-UA logger.info("Adding pdf/ua content."); try { PDDocumentCatalog root = doc.getDocumentCatalog(); PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot(); if (structureTreeRoot != null) { logger.info("Tree Root: {}", structureTreeRoot.toString()); List<Object> kids = structureTreeRoot.getKids(); if (kids == null) { logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document"); } PDStructureElement docElement = null; for (Object k : kids) { if (k instanceof PDStructureElement) { docElement = (PDStructureElement) k; break; } } PDStructureElement sigBlock = new PDStructureElement("Form", docElement); // create object dictionary and add as child element COSDictionary objectDic = new COSDictionary(); objectDic.setName("Type", "OBJR"); objectDic.setItem("Pg", signatureField.getWidget().getPage()); objectDic.setItem("Obj", signatureField.getWidget()); List<Object> l = new ArrayList<Object>(); l.add(objectDic); sigBlock.setKids(l); sigBlock.setPage(signatureField.getWidget().getPage()); sigBlock.setTitle("Signature Table"); sigBlock.setParent(docElement); docElement.appendKid(sigBlock); // Create and add Attribute dictionary to mitigate PAC // warning COSDictionary sigBlockDic = (COSDictionary) sigBlock.getCOSObject(); COSDictionary sub = new COSDictionary(); sub.setName("O", "Layout"); sub.setName("Placement", "Block"); sigBlockDic.setItem(COSName.A, sub); sigBlockDic.setNeedToBeUpdated(true); // Modify number tree PDNumberTreeNode ntn = structureTreeRoot.getParentTree(); int parentTreeNextKey = structureTreeRoot.getParentTreeNextKey(); if (ntn == null) { ntn = new PDNumberTreeNode(objectDic, null); logger.info("No number-tree-node found!"); } COSArray ntnKids = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.KIDS); COSArray ntnNumbers = (COSArray) ntn.getCOSObject().getDictionaryObject(COSName.NUMS); if (ntnNumbers == null && ntnKids != null) {//no number array, so continue with the kids array //create dictionary with limits and nums array COSDictionary pTreeEntry = new COSDictionary(); COSArray limitsArray = new COSArray(); //limits for exact one entry limitsArray.add(COSInteger.get(parentTreeNextKey)); limitsArray.add(COSInteger.get(parentTreeNextKey)); COSArray numsArray = new COSArray(); numsArray.add(COSInteger.get(parentTreeNextKey)); numsArray.add(sigBlock); pTreeEntry.setItem(COSName.NUMS, numsArray); pTreeEntry.setItem(COSName.LIMITS, limitsArray); PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry, PDNumberTreeNode.class); ntnKids.add(newKidsElement); ntnKids.setNeedToBeUpdated(true); } else if (ntnNumbers != null && ntnKids == null) { int arrindex = ntnNumbers.size(); ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey)); ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject()); ntnNumbers.setNeedToBeUpdated(true); structureTreeRoot.setParentTree(ntn); } else if (ntnNumbers == null && ntnKids == null) { //document is not pdfua conform before signature creation throw new PdfAsException("error.pdf.sig.pdfua.1"); } else { //this is not allowed throw new PdfAsException("error.pdf.sig.pdfua.1"); } // set StructureParent for signature field annotation signatureField.getWidget().setStructParent(parentTreeNextKey); //Increase the next Key value in the structure tree root structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1); // add the Tabs /S Element for Tabbing through annots PDPage p = signatureField.getWidget().getPage(); p.getCOSObject().setName("Tabs", "S"); p.getCOSObject().setNeedToBeUpdated(true); //check alternative signature field name if (signatureField != null) { if (signatureField.getAlternateFieldName().equals("")) signatureField.setAlternateFieldName(sigFieldName); } ntn.getCOSObject().setNeedToBeUpdated(true); sigBlock.getCOSObject().setNeedToBeUpdated(true); structureTreeRoot.getCOSObject().setNeedToBeUpdated(true); objectDic.setNeedToBeUpdated(true); docElement.getCOSObject().setNeedToBeUpdated(true); } } catch (Throwable e) { if (signatureProfileSettings.isPDFUA() == true) { logger.error("Could not create PDF-UA conform document!"); throw new PdfAsException("error.pdf.sig.pdfua.1", e); } else { logger.info("Could not create PDF-UA conform signature"); } } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); synchronized (doc) { doc.saveIncremental(bos); byte[] outputDocument = bos.toByteArray(); /* Check if resulting pdf is PDF-A conform */ //if (signatureProfileSettings.isPDFA()) { // // TODO: run preflight parser // runPDFAPreflight(outputDocument); //} pdfObject.setSignedDocument(outputDocument); } } finally { if (options != null) { if (options.getVisualSignature() != null) { options.getVisualSignature().close(); } } } System.gc(); } catch (IOException e) { logger.warn(MessageResolver.resolveMessage("error.pdf.sig.01"), e); throw new PdfAsException("error.pdf.sig.01", e); } finally { if (doc != null) { try { doc.close(); } catch (IOException e) { logger.debug("Failed to close COS Doc!", e); // Ignore } } logger.debug("Signature done!"); } }
From source file:blankpdf.BlankPDF.java
public void TestePDF() { String fileName = "Sparta.pdf"; // name of our file PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page);//from www . ja v a 2 s. c o m PDImageXObject imagem; PDPageContentStream content; try { content = new PDPageContentStream(doc, page); //OBSERVAO IMPORTANTE -- //Para funcionar sem tratamento de string criar o projeto em pasta sem caracteres //especiais nem ESPAO EM BRANCO imagem = PDImageXObject.createFromFile(getClass().getResource("sparta.png").getPath(), doc); ///Users/marcelosiedler/Google%20Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/silviosantos.jpg //imagem = PDImageXObject.createFromFile("/Users/marcelosiedler/Google Drive/bage/2016_02/BlankPDF/build/classes/blankpdf/sparta.png", doc); content.beginText(); content.setFont(PDType1Font.TIMES_BOLD, 26); content.newLineAtOffset(10, 750); content.showText("Gincana IFSUL2"); content.endText(); content.beginText(); content.setFont(PDType1Font.TIMES_BOLD, 16); content.newLineAtOffset(80, 700); content.showText("Turma : "); content.endText(); content.drawImage(imagem, 75, 500); content.close(); doc.save(fileName); doc.close(); System.out.println("Arquivo criado em : " + System.getProperty("user.dir")); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:ch.dowa.jassturnier.pdf.PdfGenerator.java
public void exportTemplateWithTable(TableBuilder tableBuilder, String fileName, String title) throws IOException { String vLogoPath = !ResourceLoader.readProperty("LOGOPATH").isEmpty() ? ResourceLoader.readProperty("LOGOPATH") : null;/*from w ww . j ava 2 s .c om*/ final PDDocument document = new PDDocument(); boolean firstPage = true; PDImageXObject image = null; float imageStartX = 0F; float imageStartY = 0F; PDRectangle imgSize = null; TableDrawer drawer = TableDrawer.builder().table(tableBuilder.build()).startX(docContentStartX()) .startY(docContentStartY()).endY(documentPadding).build(); if (vLogoPath != null) { image = PDImageXObject.createFromFile(vLogoPath, document); imgSize = getImageSizePdf(image); imageStartX = imgEndX() - imgSize.getWidth(); imageStartY = imgEndY() - imgSize.getHeight(); } do { PDPage page = new PDPage(pageFormat); document.addPage(page); try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { if (firstPage) { contentStream.beginText(); contentStream.setFont(STANDART_FONT_BOLD, 14); contentStream.newLineAtOffset(docTitelStartX(), docTitelStartY()); contentStream.showText(title); contentStream.endText(); if (image != null) { contentStream.drawImage(image, imageStartX, imageStartY, imgSize.getWidth(), imgSize.getHeight()); } drawer.startY(docContentSartFirsPageY()); firstPage = false; } drawer.contentStream(contentStream).draw(); } drawer.startY(docContentStartY()); } while (!drawer.isFinished()); document.save(fileName); document.close(); }
From source file:ch.dowa.jassturnier.pdf.PdfGenerator.java
public void exportTemplateWithTableMultiPage(HashMap<String, Table.TableBuilder> tableBuildersMap, String fileName) throws IOException { String vLogoPath = !ResourceLoader.readProperty("LOGOPATH").isEmpty() ? ResourceLoader.readProperty("LOGOPATH") : null;/*from w w w .j a v a2 s . c om*/ PDDocument mainDoc = new PDDocument(); PDFMergerUtility merger = new PDFMergerUtility(); for (Map.Entry<String, TableBuilder> entry : tableBuildersMap.entrySet()) { String title = entry.getKey(); TableBuilder tableBuilder = entry.getValue(); final PDDocument documentPage = new PDDocument(); boolean firstPage = true; PDImageXObject image = null; float imageStartX = 0F; float imageStartY = 0F; PDRectangle imgSize = null; TableDrawer drawer = TableDrawer.builder().table(tableBuilder.build()).startX(docContentStartX()) .startY(docContentStartY()).endY(documentPadding).build(); if (vLogoPath != null) { image = PDImageXObject.createFromFile(vLogoPath, documentPage); imgSize = getImageSizePdf(image); imageStartX = imgEndX() - imgSize.getWidth(); imageStartY = imgEndY() - imgSize.getHeight(); } do { PDPage page = new PDPage(pageFormat); documentPage.addPage(page); try (PDPageContentStream contentStream = new PDPageContentStream(documentPage, page)) { if (firstPage) { contentStream.beginText(); contentStream.setFont(STANDART_FONT_BOLD, 14); contentStream.newLineAtOffset(docTitelStartX(), docTitelStartY()); contentStream.showText(title); contentStream.endText(); if (image != null) { contentStream.drawImage(image, imageStartX, imageStartY, imgSize.getWidth(), imgSize.getHeight()); } drawer.startY(docContentSartFirsPageY()); firstPage = false; } drawer.contentStream(contentStream).draw(); } drawer.startY(docContentStartY()); } while (!drawer.isFinished()); merger.appendDocument(mainDoc, documentPage); } mainDoc.save(fileName); mainDoc.close(); }
From source file:ch.eggbacon.app.pdf.PDFCreator.java
License:Open Source License
public void drawHeader(PDPageContentStream contentStream) throws IOException { PDImageXObject img = PDImageXObject.createFromFile("web/img/logo.png", doc); contentStream.drawImage(img, PDFConstants.MARGIN, PDFConstants.PAPER_HEIGHT - 40, 47, 30); contentStream.setFont(PDType1Font.HELVETICA_BOLD, 18); contentStream.beginText();//www .j a v a 2s . c o m contentStream.moveTextPositionByAmount(PDFConstants.MARGIN + 50, PDFConstants.PAPER_HEIGHT - 30); contentStream.drawString("Egg & Bacon Hotel"); contentStream.endText(); }
From source file:com.encodata.PDFSigner.PDFSigner.java
public void createPDFFromImage(String inputFile, String imagePath, String outputFile, String x, String y, String width, String height, CallbackContext callbackContext) throws IOException { if (inputFile == null || imagePath == null || outputFile == null) { callbackContext.error("Expected localFile and remoteFile."); } else {//w w w . j a v a2s . c om // the document PDDocument doc = null; try { doc = PDDocument.load(new File(inputFile)); //we will add the image to the first page. PDPage page = doc.getPage(0); // createFromFile is the easiest way with an image file // if you already have the image in a BufferedImage, // call LosslessFactory.createFromImage() instead PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc); PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true); // contentStream.drawImage(ximage, 20, 20 ); // better method inspired by http://stackoverflow.com/a/22318681/535646 // reduce this value if the image is too large float scale = 1f; contentStream.drawImage(pdImage, Float.parseFloat(x), Float.parseFloat(y), Float.parseFloat(width) * scale, Float.parseFloat(height) * scale); contentStream.close(); doc.save(outputFile); callbackContext.success(outputFile); } catch (Exception e) { callbackContext.error(e.toString()); } finally { if (doc != null) { doc.close(); } } } }
From source file:controladores4.controladorReportes.java
public boolean generarInformeCobranza(final JTable tabla, final int[] rows) { DateFormat perDate = new SimpleDateFormat("MMMM-yyyy"); DateFormat date = new SimpleDateFormat("dd-MM-yyyy"); final String per = date.format(new Date()); final NumberFormat FORMAT = NumberFormat.getCurrencyInstance(); final DecimalFormatSymbols dfs = new DecimalFormatSymbols(); Thread runnable = new Thread() { public void run() { try { dfs.setCurrencySymbol("$ "); dfs.setGroupingSeparator('.'); dfs.setMonetaryDecimalSeparator('.'); ((DecimalFormat) FORMAT).setDecimalFormatSymbols(dfs); String path = "Informes de cobranza/" + tabla.getValueAt(rows[0], 2); File dir = new File(path); dir.mkdirs();/* ww w. j a v a2s . c om*/ String fileName = path + "/" + per + ".pdf"; // name of our file PDDocument doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream content = new PDPageContentStream(doc, page); int total = 0; modeloClientes model = new modeloClientes(); String[] data = model.obtenerRutContactoPorRazon(tabla.getValueAt(rows[0], 2).toString()); try { //HEADER content.beginText(); content.setFont(PDType1Font.HELVETICA, 10); content.setLeading(14.5f); content.moveTextPositionByAmount(50, 770); content.endText(); content.drawLine(30, 750, 600, 750); File imagen = new File(("src/icono/Logo_Gruas.bmp")); String imPath = imagen.getAbsolutePath(); System.out.println(imPath); PDImageXObject image = PDImageXObject.createFromFile(imPath, doc); content.drawImage(image, 50, 600); content.beginText(); content.moveTextPositionByAmount(400, 680); content.showText("INFORME COBRANZA"); content.newLine(); content.showText(per); content.newLineAtOffset(-130, -80); content.showText("CLIENTE"); content.newLine(); content.endText(); content.drawLine(30, 580, 600, 580); content.beginText(); content.moveTextPositionByAmount(50, 560); content.showText("Rut: "); content.newLineAtOffset(100, 0); content.showText(data[0]); content.newLineAtOffset(-100, -15); content.showText("Razn Social:"); content.newLineAtOffset(100, 0); content.showText(data[1]); content.newLineAtOffset(-100, -15); content.showText("Contacto:"); content.newLineAtOffset(100, 0); content.newLine(); content.endText(); content.drawLine(30, 510, 600, 510); content.beginText(); content.moveTextPositionByAmount(50, 480); content.showText( "Estimado cliente, las facturas que se exponen a continuacin se encuentran pendientes"); content.newLine(); content.showText("de pago. Favor regularizar la situacin."); content.endText(); content.drawLine(30, 440, 600, 440); content.beginText(); content.moveTextPositionByAmount(70, 430); content.showText("N Folio"); content.newLineAtOffset(70, 0); content.showText("Fecha"); content.newLineAtOffset(70, 0); content.showText("Das emisin"); content.newLineAtOffset(80, 0); content.showText("Total factura"); content.newLineAtOffset(80, 0); content.showText("Monto abono"); content.newLineAtOffset(80, 0); content.showText("Saldo deuda"); content.newLineAtOffset(80, 0); content.endText(); content.drawLine(30, 425, 600, 425); content.beginText(); content.moveTextPositionByAmount(75, 390); for (int row : rows) { String folio = tabla.getValueAt(row, 0).toString(); String fecha = tabla.getValueAt(row, 3).toString(); String dias = tabla.getValueAt(row, 4).toString(); int monto = Integer.parseInt(tabla.getValueAt(row, 7).toString()); int abono = Integer.parseInt(tabla.getValueAt(row, 11).toString()); int saldo = Integer.parseInt(tabla.getValueAt(row, 12).toString()); total += saldo; content.showText(folio); content.newLineAtOffset(60, 0); content.showText(fecha); content.newLineAtOffset(90, 0); content.showText(dias); content.newLineAtOffset(70, 0); content.showText(FORMAT.format(monto)); content.newLineAtOffset(80, 0); content.showText(FORMAT.format(abono)); content.newLineAtOffset(80, 0); content.showText(FORMAT.format(saldo)); content.newLineAtOffset(-380, -15); } content.newLineAtOffset(310, -45); content.showText("Total deuda"); content.newLineAtOffset(70, 0); content.showText(FORMAT.format(total)); content.endText(); content.close(); doc.save(fileName); // saving as pdf file with name perm doc.close(); // cleaning memory } catch (Exception e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "Informe de cobranza generado con xito", "Operacin exitosa", JOptionPane.INFORMATION_MESSAGE); // liquidaciones.limpiarRemuneraciones(); } catch (Exception e) { e.printStackTrace(); } } }; //runnable.run(); runnable.start(); return true; }
From source file:fys.StatistiekenController.java
@FXML private void handleExportToPDFAction(ActionEvent event) throws IOException { if ((dateFrom.getText() == null || dateFrom.getText().trim().isEmpty()) || (dateTo.getText() == null || dateTo.getText().trim().isEmpty())) { ErrorLabel.setText(taal[93]);//from w w w . j av a 2 s .c o m ErrorLabel.setVisible(true); } else { String dateFromInput = dateFrom.getText(); String dateToInput = dateTo.getText(); //Doe dit alleen wanneer er waardes zijn ingevuld. lineChart.setAnimated(false); pieChart.setAnimated(false); //PIECHART //Maak alle data en aantallen weer leeg. int luggage = 0, foundAmount = 0, lostAmount = 0, destroyAmount = 0, settleAmount = 0, neverFoundAmount = 0, depotAmount = 0; int jan = 0, feb = 0, mar = 0, apr = 0, mei = 0, jun = 0, jul = 0, aug = 0, sep = 0, okt = 0, nov = 0, dec = 0; total = 0; series.getData().clear(); pieChartData = FXCollections.observableArrayList(); //Krijg alle data voor de pietchart die tussen de periode van DateFrom en DateTo ligt. try { conn = fys.connectToDatabase(conn); stmt = conn.createStatement(); //connectToDatabase(conn, stmt, "test", "root", "root"); String sql = "SELECT status, date, COUNT(status) AS Count FROM bagagedatabase.luggage_status " + "WHERE date >= \"" + fys.convertToDutchDate(dateFromInput) + "\" " + "AND date <= \"" + fys.convertToDutchDate(dateToInput) + "\" " + "GROUP BY status"; //Voeg alle aantallen per status toe aan variabelen. try (ResultSet rs = stmt.executeQuery(sql)) { while (rs.next()) { luggage++; //Retrieve by column name foundAmount = (rs.getInt("status") == 0 ? rs.getInt("Count") : foundAmount); lostAmount = (rs.getInt("status") == 1 ? rs.getInt("Count") : lostAmount); destroyAmount = (rs.getInt("status") == 2 ? rs.getInt("Count") : destroyAmount); settleAmount = (rs.getInt("status") == 3 ? rs.getInt("Count") : settleAmount); neverFoundAmount = (rs.getInt("status") == 4 ? rs.getInt("Count") : neverFoundAmount); depotAmount = (rs.getInt("status") == 5 ? rs.getInt("Count") : depotAmount); } } } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } //Voeg de waardes toe aan de array. pieChartData = FXCollections.observableArrayList(new PieChart.Data(ExportToPdfTexts[15], foundAmount), new PieChart.Data(ExportToPdfTexts[16], lostAmount), new PieChart.Data(ExportToPdfTexts[17], destroyAmount), new PieChart.Data(ExportToPdfTexts[18], settleAmount), new PieChart.Data(ExportToPdfTexts[19], neverFoundAmount), new PieChart.Data(ExportToPdfTexts[20], depotAmount)); //Update de titel pieChart.setTitle(ExportToPdfTexts[0]); //Update de piechart met de gevraagde gegevens. pieChart.setData(pieChartData); //Voor elke aantal tel ze met elkaar op en sla het op bij total. for (PieChart.Data d : pieChart.getData()) { total += d.getPieValue(); } //Verander de tekst van elke piechartdata. naar: (aantal statusnaam: percentage). pieChartData.forEach(data -> data.nameProperty().bind(Bindings.concat((int) data.getPieValue(), " ", data.getName(), ": ", (total == 0 || (int) data.getPieValue() == 0) ? 0 : (int) (data.getPieValue() / total * 100), "%"))); //LINECHART //Krijg alle data voor de linechart die tussen de periode van DateFrom en DateTo ligt. try { conn = fys.connectToDatabase(conn); stmt = conn.createStatement(); String sql = "SELECT date, COUNT(date) as Count FROM bagagedatabase.luggage_status " + "WHERE status = 6 AND date >= \"" + fys.convertToDutchDate(dateFromInput) + "\" " + "AND date <= \"" + fys.convertToDutchDate(dateToInput) + "\" " + "GROUP BY date"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { //Retrieve by column name //Voeg alle aantallen per maand toe aan variabelen. if (rs.getString("date") != null) { //Krijg van elke date record de maand eruit. String str[] = rs.getString("date").split("-"); int month = Integer.parseInt(str[1]); jan = (month == 1 ? jan += rs.getInt("Count") : jan); feb = (month == 2 ? feb += rs.getInt("Count") : feb); mar = (month == 3 ? mar += rs.getInt("Count") : mar); apr = (month == 4 ? apr += rs.getInt("Count") : apr); mei = (month == 5 ? jan += rs.getInt("Count") : mei); jun = (month == 6 ? jun += rs.getInt("Count") : jun); jul = (month == 7 ? jul += rs.getInt("Count") : jul); aug = (month == 8 ? aug += rs.getInt("Count") : aug); sep = (month == 9 ? sep += rs.getInt("Count") : sep); okt = (month == 10 ? okt += rs.getInt("Count") : okt); nov = (month == 11 ? nov += rs.getInt("Count") : nov); dec = (month == 12 ? dec += rs.getInt("Count") : dec); } } rs.close(); conn.close(); } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } //Update de titel lineChart.setTitle(ExportToPdfTexts[1]); //Update de linechart naar de waardes die gewenst is. series.setName(ExportToPdfTexts[2]); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[3], jan)); series.getData().add(new XYChart.Data(ExportToPdfTexts[4], feb)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[5], mar)); series.getData().add(new XYChart.Data(ExportToPdfTexts[6], apr)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[7], mei)); series.getData().add(new XYChart.Data(ExportToPdfTexts[8], jun)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[9], jul)); series.getData().add(new XYChart.Data(ExportToPdfTexts[10], aug)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[11], sep)); series.getData().add(new XYChart.Data(ExportToPdfTexts[12], okt)); series.getData().add(new XYChart.Data<>(ExportToPdfTexts[13], nov)); series.getData().add(new XYChart.Data(ExportToPdfTexts[14], dec)); //Update de piechart en linechart voordat er een screenshot van genomen wordt. lineChart.applyCss(); lineChart.layout(); pieChart.applyCss(); pieChart.layout(); //Maak een screenshot van de piechart en linechart. savePieChartAsPng(); saveLineChartAsPng(); try { //Krijg de datum van vandaag voor pdf. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String dateString = dateFormat.format(date); //Krijg de content van de template pdf en maake nieuw pdf aan. File pdfdoc = new File("src/fys/templates/statisticstemplate.pdf"); PDDocument document = null; document = PDDocument.load(pdfdoc); PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); List<PDField> fields = acroForm.getFields(); // set the text in the form-field <-- does work //Verander voor elk veld de waardes. for (PDField field : fields) { if (field.getFullyQualifiedName().equals("found")) { field.setValue(String.valueOf(foundAmount)); } if (field.getFullyQualifiedName().equals("lost")) { field.setValue(String.valueOf(lostAmount)); } if (field.getFullyQualifiedName().equals("destroyed")) { field.setValue(String.valueOf(destroyAmount)); } if (field.getFullyQualifiedName().equals("completed")) { field.setValue(String.valueOf(settleAmount)); } if (field.getFullyQualifiedName().equals("neverfound")) { field.setValue(String.valueOf(neverFoundAmount)); } if (field.getFullyQualifiedName().equals("depot")) { field.setValue(String.valueOf(depotAmount)); } if (field.getFullyQualifiedName().equals("jan")) { field.setValue(String.valueOf(jan)); } if (field.getFullyQualifiedName().equals("feb")) { field.setValue(String.valueOf(feb)); } if (field.getFullyQualifiedName().equals("mar")) { field.setValue(String.valueOf(mar)); } if (field.getFullyQualifiedName().equals("apr")) { field.setValue(String.valueOf(apr)); } if (field.getFullyQualifiedName().equals("may")) { field.setValue(String.valueOf(mei)); } if (field.getFullyQualifiedName().equals("jun")) { field.setValue(String.valueOf(jun)); } if (field.getFullyQualifiedName().equals("jul")) { field.setValue(String.valueOf(jul)); } if (field.getFullyQualifiedName().equals("aug")) { field.setValue(String.valueOf(aug)); } if (field.getFullyQualifiedName().equals("sep")) { field.setValue(String.valueOf(sep)); } if (field.getFullyQualifiedName().equals("oct")) { field.setValue(String.valueOf(okt)); } if (field.getFullyQualifiedName().equals("nov")) { field.setValue(String.valueOf(nov)); } if (field.getFullyQualifiedName().equals("dec")) { field.setValue(String.valueOf(dec)); } if (field.getFullyQualifiedName().equals("date")) { field.setValue(String.valueOf(dateString)); } if (field.getFullyQualifiedName().equals("period")) { field.setValue(String.valueOf(dateFromInput + " | " + dateToInput)); } } //Retrieving the page PDPage page = document.getPage(0); //Creating PDImageXObject object loginController login = new loginController(); PDImageXObject pieChartImage = PDImageXObject .createFromFile("src/fys/statistieken/PieChart_" + login.getUsersName() + ".png", document); PDImageXObject lineChartImage = PDImageXObject.createFromFile( "src/fys/statistieken/LineChart_" + login.getUsersName() + ".png", document); //creating the PDPageContentStream object PDPageContentStream contents = new PDPageContentStream(document, page, true, true, true); //Drawing the image in the PDF document contents.drawImage(pieChartImage, 75, 0, 350, 300); contents.drawImage(lineChartImage, 425, 0, 350, 300); //Closing the PDPageContentStream object contents.close(); //Sla het docment op. document.save("src/fys/statistieken/statistics" + dateFromInput + dateToInput + ".pdf"); document.close(); //Verwijder de plaatjes die waren opgeslagen. savePieChartAsPng().delete(); saveLineChartAsPng().delete(); //Sluit de popup home_pane.setDisable(false); pdfPane.setVisible(false); } catch (IOException ex) { Logger.getLogger(StatistiekenController.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:merge_split.MergeSplit.java
License:Apache License
private void RotateButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RotateButton1ActionPerformed PDDocument document = new PDDocument(); InputStream in = null;/* www . j a v a2 s .co m*/ BufferedImage bimg = null; try { in = new FileInputStream((String) ImageFileField.getText()); bimg = ImageIO.read(in); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Image could not be read.", "Image could not be read", JOptionPane.WARNING_MESSAGE); } float width = bimg.getWidth(); float height = bimg.getHeight(); PDPage page = new PDPage(new PDRectangle(width, height)); document.addPage(page); PDImageXObject imgpdf; try { imgpdf = PDImageXObject.createFromFile((String) ImageFileField.getText(), document); try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) { contentStream.drawImage(imgpdf, 0, 0); } in.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Image could not be converted.", "Proccess could not be finished", JOptionPane.WARNING_MESSAGE); } String destination = ImageDestinationField.getText() + "\\" + ImageNameField.getText() + ".pdf"; PDDocumentInformation info = document.getDocumentInformation(); info.setAuthor(ImageAuthorField.getText()); File output = new File(destination); try { document.save(output); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Not all fields were filled.", "Input Problem", JOptionPane.WARNING_MESSAGE); } try { document.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Not all fields were filled.", "Input Problem", JOptionPane.WARNING_MESSAGE); } }
From source file:model.util.pdf.PDFUtils.java
License:Apache License
/** * Test: Create pdf from image and pdf file. * * @param _inputFile pdf input/*from w w w .java 2 s .c o m*/ * @param _imagePath image input * @param _outputFile pdf output * * @throws IOException occurs if reading the data fails. */ public void saveAsPdf(String _imagePath, String _outputFile) throws IOException { PDDocument doc = null; try { // create new document and insert empty page to the document. doc = new PDDocument(); PDPage page = new PDPage(); doc.addPage(page); // createFromFile is the easiest way with an image file // if you already have the image in a BufferedImage, // call LosslessFactory.createFromImage() instead PDImageXObject pdImage = PDImageXObject.createFromFile(_imagePath, doc); PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true); // contentStream.drawImage(ximage, 20, 20 ); // better method inspired by http://stackoverflow.com/a/22318681/535646 // reduce this value if the image is too large float scale = 1f; contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale); contentStream.close(); doc.save(_outputFile); } finally { if (doc != null) { doc.close(); } } }