private static PdfPCell getPhotoCell(BufferedImage bufferedImage, float scalePercent, boolean isHorizontallyCentered) throws BadElementException, IOException { Image jpeg = Image.getInstance(bufferedImage, null); jpeg.scalePercent(scalePercent); jpeg.setAlignment(Image.MIDDLE); PdfPCell photoCell = new PdfPCell(jpeg); photoCell.setBorder(0); if (isHorizontallyCentered) { photoCell.setHorizontalAlignment(Element.ALIGN_CENTER); } else { photoCell.setHorizontalAlignment(Element.ALIGN_RIGHT); } photoCell.setVerticalAlignment(Element.ALIGN_TOP); int height = (int) Math.ceil(bufferedImage.getHeight() * scalePercent / 100); photoCell.setFixedHeight(height); return photoCell; }
public ImageInstance getImageByFile( PdfContentByte cb , File file ) throws IOException, BadElementException{ Image image = null; ImageInstance instance = null; if( file.getName().toLowerCase().endsWith( ".pdf")){ PdfReader reader = new PdfReader( file.getAbsolutePath() ); PdfImportedPage p = cb.getPdfWriter().getImportedPage(reader, 1); image = Image.getInstance(p); instance = new ImageInstance(image, reader); }else{ image = Image.getInstance( file.getAbsolutePath() ); instance = new ImageInstance(image, null); } instances.add(instance); return instance; }
public void IMGToPDF(String RESOURCES, String result) throws DocumentException, FileNotFoundException, BadElementException, IOException{ ProgressBar progrsbar=new ProgressBar(); progrsbar.showProgress(); Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result)); // step 3 document.open(); // step 4 Image img; img = Image.getInstance(RESOURCES); Image.getInstance(img); document.add(img); progrsbar.updatePercent(100); document.close(); }
private List<Element> renderGral(String raw) throws BadElementException, IOException { ChartDescriptor descriptor = new ChartDescriptorParser().parse(raw); PdfContentByte cb = writer.get().getDirectContent(); float width = (float) descriptor.getWidth(); float height = (float) descriptor.getHeight(); PdfTemplate template = cb.createTemplate(width, height); Graphics2D g2 = new PdfGraphics2D(template, width, height); GralRenderer renderer = new GralRenderer(); renderer.render(g2, descriptor); ArrayList<Element> elements = new ArrayList<Element>(1); elements.add(new ImgTemplate(template)); return elements; }
private void createHeader(final PdfPTable table, final String challengeTitle, final String catTitle, final String division, final String judgingGroup, final Tournament tournament) throws BadElementException { final PdfPCell tournamentCell = PdfUtils.createHeaderCell(String.format("%s - %s", challengeTitle, tournament.getDescription())); tournamentCell.setColspan(4); table.addCell(tournamentCell); final PdfPCell categoryHeader = PdfUtils.createHeaderCell(String.format("Category: %s - Award Group: %s - JudgingGroup: %s", catTitle, division, judgingGroup)); categoryHeader.setColspan(4); table.addCell(categoryHeader); table.addCell(PdfUtils.createHeaderCell(TournamentSchedule.TEAM_NUMBER_HEADER)); table.addCell(PdfUtils.createHeaderCell(TournamentSchedule.TEAM_NAME_HEADER)); table.addCell(PdfUtils.createHeaderCell(TournamentSchedule.ORGANIZATION_HEADER)); table.addCell(PdfUtils.createHeaderCell("Scaled Score")); table.setHeaderRows(3); }
/** * Create itextPdf image object with visitor signature. * * @param file * @param imgHeight * @param imgWidth * @return com.itextpdf.text.Image */ public static Image createNDAImage(File file, int imgHeight, int imgWidth) { try { Image image = Image.getInstance(file.getAbsolutePath()); if (imgHeight!=0 && imgWidth!=0) { image.scaleAbsolute(imgWidth, imgHeight); } else { image.scaleAbsolute(230, 140); } image.setAbsolutePosition(70, 450); return image; } catch (BadElementException | IOException e) { logger.error("Exception while creating image for NDA file. ",e); return null; } }
private void dataTableTitile(Document documento, String data) throws IOException, BadElementException, DocumentException { try { pTableEmpresaPricipal = new PdfPTable(new float[]{15f, 85f}); pTableEmpresaInforImpres1 = new PdfPTable(1); pTableEmpresaInforImpres5 = new PdfPTable(1); PdfPCell pCellNomeEmpresa = new PdfPCell(new Phrase(Empresa.NOME, fontCabecalhoNG)); pCellNomeEmpresa.setBorder(0); PdfPCell pCellNomeEndereco = new PdfPCell(new Phrase(Empresa.ENDERECO, fontCabecalhoN)); pCellNomeEndereco.setBorder(0); PdfPCell pCellCaixaPostal = new PdfPCell(new Phrase(Empresa.CAIXAPOSTAL, fontCabecalhoN)); pCellCaixaPostal.setBorder(0); PdfPCell pCellTeleFax = new PdfPCell(new Phrase(Empresa.TELEFAX + " " + ConfigDoc.Empresa.EMAIL, fontCabecalhoN)); pCellTeleFax.setBorder(0); PdfPCell pCellSociedade = new PdfPCell(new Phrase(Empresa.SOCIEDADE, fontCabecalhoN)); pCellSociedade.setBorder(0); Image imageEmpresa = Image.getInstance("logo.png"); imageEmpresa.scaleToFit(120f, 85f); pTableEmpresaInforImpres1.addCell(pCellNomeEmpresa); pTableEmpresaInforImpres1.addCell(pCellNomeEndereco); pTableEmpresaInforImpres1.addCell(pCellCaixaPostal); pTableEmpresaInforImpres1.addCell(pCellTeleFax); pTableEmpresaInforImpres1.addCell(pCellSociedade); PdfPCell cellTabela3 = new PdfPCell(pTableEmpresaInforImpres1); cellTabela3.setBorder(0); pTableEmpresaInforImpres5.addCell(cellTabela3); PdfPCell cellTabela5 = new PdfPCell(pTableEmpresaInforImpres5); cellTabela5.setBorder(0); PdfPCell cellTabela6 = new PdfPCell(imageEmpresa); cellTabela6.setBorder(0); pTableEmpresaPricipal.setWidthPercentage(95); pTableEmpresaPricipal.addCell(cellTabela6); pTableEmpresaPricipal.addCell(cellTabela5); PdfPTable pTableTitulo = new PdfPTable(1); pTableTitulo.setHorizontalAlignment(Element.ALIGN_CENTER); pTableTitulo.setWidthPercentage(100); SimpleDateFormat sdfEsp = new SimpleDateFormat("MMMM, yyyy", Locale.ENGLISH); SimpleDateFormat sdf = new SimpleDateFormat("MM-yyyy"); PdfPCell cellTitulo = new PdfPCell(new Phrase("TOTAL PREMIUM COLLECTED ON TRAVEL INSURANCE AND TAXES FOR "+sdfEsp.format(sdf.parse(data)).toUpperCase(), fontCorpoNG)); cellTitulo.setBorder(0); cellTitulo.setPaddingBottom(10f); pTableTitulo.addCell(cellTitulo); pTableEmpresaPricipal.setHorizontalAlignment(Element.ALIGN_CENTER); documento.add(pTableEmpresaPricipal); documento.add(pTableNull); documento.add(pTableTitulo); } catch (ParseException ex) { Logger.getLogger(ExporOnlyViagemPdf.class.getName()).log(Level.SEVERE, null, ex); } }
/** * The <code>addImageToPdf</code> method is used to add image to pdf and make it searchable by adding image text in invisible mode * w.r.t parameter 'isPdfSearchable' passed. * * @param pdfWriter {@link PdfWriter} writer of pdf in which image has to be added * @param htmlUrl {@link HocrPage} corresponding html file for fetching text and coordinates * @param imageUrl {@link String} url of image to be added in pdf * @param isPdfSearchable true for searchable pdf else otherwise * @param widthOfLine */ private void addImageToPdf(PdfWriter pdfWriter, HocrPage hocrPage, String imageUrl, boolean isPdfSearchable, final int widthOfLine) { if (null != pdfWriter && null != imageUrl && imageUrl.length() > 0) { try { LOGGER.info("Adding image" + imageUrl + " to pdf using iText"); Image pageImage = Image.getInstance(imageUrl); float dotsPerPointX = pageImage.getDpiX() / PDF_RESOLUTION; float dotsPerPointY = pageImage.getDpiY() / PDF_RESOLUTION; PdfContentByte pdfContentByte = pdfWriter.getDirectContent(); pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY); pageImage.setAbsolutePosition(0, 0); // Add image to pdf pdfWriter.getDirectContentUnder().addImage(pageImage); pdfWriter.getDirectContentUnder().add(pdfContentByte); // If pdf is to be made searchable if (isPdfSearchable) { LOGGER.info("Adding invisible text for image: " + imageUrl); float pageImagePixelHeight = pageImage.getHeight(); Font defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK); // Fetch text and coordinates for image to be added Map<String, int[]> textCoordinatesMap = getTextWithCoordinatesMap(hocrPage, widthOfLine); Set<String> ketSet = textCoordinatesMap.keySet(); // Add text at specific location for (String key : ketSet) { int[] coordinates = textCoordinatesMap.get(key); float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX; float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY; pdfContentByte.beginText(); // To make text added as invisible pdfContentByte.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); pdfContentByte.setLineWidth(Math.round(bboxWidthPt)); // Ceil is used so that minimum font of any text is 1 // For exception of unbalanced beginText() and endText() if (bboxHeightPt > 0.0) { pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), (float) Math.ceil(bboxHeightPt)); } else { pdfContentByte.setFontAndSize(defaultFont.getBaseFont(), 1); } float xCoordinate = (float) (coordinates[0] / dotsPerPointX); float yCoordinate = (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY); pdfContentByte.moveText(xCoordinate, yCoordinate); pdfContentByte.showText(key); pdfContentByte.endText(); } } pdfContentByte.closePath(); } catch (BadElementException badElementException) { LOGGER .error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + badElementException.toString()); } catch (DocumentException documentException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + documentException.toString()); } catch (MalformedURLException malformedURLException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + malformedURLException.toString()); } catch (IOException ioException) { LOGGER.error("Error occurred while adding image" + imageUrl + " to pdf using Itext: " + ioException.toString()); } } }
/** * Returns an image from the given component path * @param pSerialisationContext The serialisation context, used to get the image from the application components table * @param pComponentPath The path to the component * @return The resolved image * @throws ExInternal If there was an error creating an image from the component file */ private Image getImageFromComponent(SerialisationContext pSerialisationContext, String pComponentPath) throws ExInternal { FoxComponent lImageComponent = FoxComponentUtils.getComponent(pSerialisationContext, pComponentPath); try { return Image.getInstance(ByteStreams.toByteArray(lImageComponent.getInputStream())); } catch (IOException | BadElementException e) { throw new ExInternal("Failed to create image from component '" + pComponentPath + "'", e); } }
private void updateImageStream(PRStream imageStream, byte[] newData) throws BadElementException, IOException, BadPdfFormatException { PdfImage image = new PdfImage(Image.getInstance(newData), "", null); if (imageStream.contains(PdfName.SMASK)) { image.put(PdfName.SMASK, imageStream.get(PdfName.SMASK)); } if (imageStream.contains(PdfName.MASK)) { image.put(PdfName.MASK, imageStream.get(PdfName.MASK)); } if (imageStream.contains(PdfName.SMASKINDATA)) { image.put(PdfName.SMASKINDATA, imageStream.get(PdfName.SMASKINDATA)); } imageStream.clear(); imageStream.putAll(image); imageStream.setDataRaw(image.getBytes()); }
PdfPCell getPiccell(int w, int h) { try { Image image = Image.getInstance("src/test/resources/mkl/testarea/itext5/content/2x2colored.png"); image.scaleAbsolute(w, h); return new PdfPCell(image); } catch (BadElementException | IOException e) { throw new RuntimeException(e); } }
private static void addBackground(PdfWriter writer) throws BadElementException, MalformedURLException, IOException, DocumentException { PdfContentByte canvas = writer.getDirectContentUnder(); canvas.saveState(); canvas.addImage(bkgnd); canvas.restoreState(); }
public static void convertToIMG(String[] RESOURCES,String result,String path,int s) throws FileNotFoundException, DocumentException, BadElementException, IOException { System.out.println(":)"); // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result)); // step 3 document.open(); // step 4 // Adding a series of images Image img; System.out.println(":) :)"); for (String image:RESOURCES) { System.out.println(image); img = Image.getInstance(path+image); document.setPageSize(img); document.newPage(); img.setAbsolutePosition(0, 0); document.add(img); System.out.println(":("); } System.out.println(":) :) :) Pdf is outo"); // step 5 document.close(); if(s==1){ JOptionPane.showMessageDialog(null,"Converted Successfully"); //JOptionPane.showMessageDialog(null, "Finished\nFile save in :\nC:\\DjVu++Task\\ImagestoPDF\\"+RESOURCES[0].substring(0,RESOURCES[0].lastIndexOf("."))+".pdf"); } }
public static void convertToIMG(String[] RESOURCES, String result, String path, int s) throws FileNotFoundException, DocumentException, BadElementException, IOException { // step 1 int percentage = 0; ProgressBar progrsbar=new ProgressBar(); progrsbar.showProgress(); Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(result)); // step 3 document.open(); // step 4 // Adding a series of images Image img; double Convertedimagescount; for (int i = 0; i < RESOURCES.length; i++) { img = Image.getInstance(String.format(path, RESOURCES[i])); Image.getInstance(img); document.add(img); Convertedimagescount =((double)i+1/(double)RESOURCES.length)*100; System.out.println(""+Convertedimagescount); percentage=(int)Convertedimagescount; } progrsbar.updatePercent(percentage); // step 5 document.close(); }
@FXML public void convertImagesToPdf() throws DocumentException, BadElementException, IOException { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select Image"); fileChooser.getExtensionFilters().addAll(new ExtensionFilter("Image Files", "*.png", "*.jpeg", "*.jpg", "*.tif")); List<File> selectedFiles = fileChooser.showOpenMultipleDialog(null); ImagesToPDF con = new ImagesToPDF(); System.err.println(selectedFiles.get(0).getAbsolutePath()); con.IMGToPDF(selectedFiles.get(0).getAbsolutePath(), "C:\\DjVu++Task\\Out.pdf"); }
public static Paragraph getPhotoInParagraph(BufferedImage bufferedImage, float scalePercent, float spacingAbove) throws BadElementException, IOException { Paragraph paragraph = new Paragraph(" ", SUB_FONT); PdfPTable table = new PdfPTable(1); table.addCell(getPhotoCell(bufferedImage, scalePercent, true)); paragraph.add(table); paragraph.setLeading(0); paragraph.setSpacingAfter(0); paragraph.setSpacingBefore(spacingAbove); return paragraph; }
public static Paragraph getPhotosInParagraph(List<BufferedImage> bufferedImages, float scalePercent, boolean isHorizontallyCentered) throws BadElementException, IOException { Paragraph paragraph = new Paragraph(" ", SUB_FONT); PdfPTable table = new PdfPTable(1); for (BufferedImage bufferedImage : bufferedImages) { table.addCell(getPhotoCell(bufferedImage, scalePercent, isHorizontallyCentered)); } table.setHorizontalAlignment(Element.ALIGN_CENTER); paragraph.add(table); paragraph.setLeading(0); paragraph.setSpacingAfter(0); paragraph.setSpacingBefore(0); return paragraph; }
/** * Create a table cell from the specified {@link Chunk}. */ public static PdfPCell createBasicCell(final Chunk chunk) throws BadElementException { final PdfPCell cell = new PdfPCell(new Phrase(chunk)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setUseDescender(true); return cell; }
/** * Create a header cell for a table. */ public static PdfPCell createHeaderCell(final String text) throws BadElementException { final Chunk chunk = new Chunk(text); chunk.getFont().setStyle(Font.BOLD); final PdfPCell cell = createBasicCell(chunk); return cell; }
/** * Create a table with the specified number of columns that is the full page * width. */ public static PdfPTable createTable(final int columns) throws BadElementException { final PdfPTable table = new PdfPTable(columns); // table.setCellsFitPage(true); table.setWidthPercentage(100); return table; }
/** * Create a table cell with the specified text and background color. */ public static PdfPCell createCell(final String text, final BaseColor backgroundColor) throws BadElementException { final PdfPCell cell = PdfUtils.createCell(text); if (null != backgroundColor) { cell.setBackgroundColor(backgroundColor); } return cell; }
public static Image readImageFromResources(String relativeImagePath) throws URISyntaxException, IOException, BadElementException { File imageFile = new File(ImageUtils.class.getResource(DIR_NAME_DATA + "/" + relativeImagePath).toURI()); return Image.getInstance(imageFile.toURL()); }
private static void addContent(File file, Document document, Chart chart) throws DocumentException, BadElementException, IOException { Paragraph paragraph = new Paragraph(); addEmptyLine(paragraph, 1); // TITLE paragraph.add(new Paragraph("Manager luggage statistics report", titleFont)); addEmptyLine(paragraph, 1); String username = (EmployeeModel.getDefault().currentEmployee.username); paragraph.add(new Paragraph("Report generated by: " + username + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ smallBold)); addEmptyLine(paragraph, 3); paragraph.add(new Paragraph("This document is a report of Manager statistics of the lost luggage system.", smallBold)); addEmptyLine(paragraph, 4); //Convert LineChart byte by byte to WritableImage WritableImage wi = chart.snapshot(null,null); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); try { ImageIO.write(SwingFXUtils.fromFXImage(wi, null), "png", byteOutput); } catch(Exception s) { System.out.println("Something went wrong with generating graph in PDF."); } graph = Image.getInstance(byteOutput.toByteArray()); document.add(paragraph); document.add(graph); //OPEN PDF AFTER CREATION try { Desktop.getDesktop().open(file); } catch (IOException ex) { System.out.println("You need to have default program set to open .PDF files."); } }
private void convertTiff(ByteArrayOutputStream outputStream, ByteArrayInputStream inStream) throws IOException, DocumentException, BadElementException, MalformedURLException { TIFFDecodeParam param = null; ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", inStream, param); System.out.println("Convert TIFF file: Found " + decoder.getNumPages() + " pages"); ArrayList<ByteArrayOutputStream> imagesStream = new ArrayList<ByteArrayOutputStream>(); int pages = decoder.getNumPages(); for (int i = 0; i < pages; i++) { RenderedImage render = decoder.decodeAsRenderedImage(i); PlanarImage op = new NullOpImage(render, null, null, OpImage.OP_IO_BOUND); BufferedImage imageBuffer = op.getAsBufferedImage(); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(imageBuffer, "jpg", os); imagesStream.add(os); } if (imagesStream.size() > 0) { Document document = new Document(PageSize.A4.rotate()); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); Iterator<ByteArrayOutputStream> iterator = imagesStream.iterator(); while (iterator.hasNext()) { document.newPage(); Image jpg = Image.getInstance(iterator.next().toByteArray()); jpg.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight()); document.add(jpg); } document.close(); writer.flush(); writer.close(); } }
/** * Write a column's value to a iText document. * @see org.displaytag.render.TableWriterTemplate#writeColumnValue(Object,org.displaytag.model.Column) */ @Override protected void writeColumnValue(Object value, Column column) throws BadElementException { this.table.addCell(getCell(value)); }
/** * Create a table cell with the specified text. */ public static PdfPCell createCell(final String text) throws BadElementException { final PdfPCell cell = createBasicCell(new Chunk(text)); return cell; }