List of usage examples for com.itextpdf.text.pdf PdfWriter open
@Override public void open()
Document
has been opened and that Elements
can be added. From source file:ImagetoPDF.java
public void convertToPDF(String folderName, String fileName, float compressionFactor) throws DocumentException, FileNotFoundException, BadElementException, IOException { File folder = new File(folderName); File[] listOfFiles = folder.listFiles(); Image img = Image.getInstance(listOfFiles[0].getAbsolutePath()); float width, height, temp; width = img.getWidth();/*from w w w. j a v a2 s .co m*/ height = img.getHeight(); if (height < width) { temp = height; height = width; width = height; } Rectangle pageSize = new Rectangle(width, height); Document document = new Document(pageSize, 0, 0, 0, 0); for (int i = 0; i < listOfFiles.length; i++) { enhance(listOfFiles[i].getAbsolutePath()); } float scalar; PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); writer.open(); writer.setCompressionLevel(5); document.open(); for (int i = 0; i < listOfFiles.length; i++) { img = Image.getInstance(listOfFiles[i].getAbsolutePath()); if (img.getWidth() > img.getHeight()) { img.setRotationDegrees(270f); } scalar = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin() - 0) / img.getWidth()) * 100; img.scalePercent(scalar); document.add(img); } document.close(); writer.close(); }
From source file:es.jscan.Pantallas.PantallaPrincipal.java
License:Apache License
@Action public Boolean guardarPdf() { if (contimagen < 1) { return false; }/*from w w w . j a va 2 s .co m*/ final PantallaBarra pantbarra = new PantallaBarra(PantallaPrincipal.this, false); pantbarra.setTitle("Generando fichero de destino"); pantbarra.botonParar.setVisible(false); errorpdf = false; new Thread() { @Override public void run() { Document pdfDocument = new Document(); // Document pdfDocument = new Document(PageSize.A4, 0, 0, 0, 0); Calendar cal = Calendar.getInstance(); String anio = String.valueOf(cal.get(Calendar.YEAR)); String mes = String.valueOf((cal.get(Calendar.MONTH) + 1)).length() == 1 ? "0" + String.valueOf((cal.get(Calendar.MONTH) + 1)) : String.valueOf((cal.get(Calendar.MONTH) + 1)); String dia = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)).length() == 1 ? "0" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) : String.valueOf(cal.get(Calendar.DAY_OF_MONTH)); String hora = String.valueOf(cal.get(Calendar.HOUR_OF_DAY)).length() == 1 ? "0" + String.valueOf(cal.get(Calendar.HOUR_OF_DAY)) : String.valueOf(cal.get(Calendar.HOUR_OF_DAY)); String minuto = String.valueOf(cal.get(Calendar.MINUTE)).length() == 1 ? "0" + String.valueOf(cal.get(Calendar.MINUTE)) : String.valueOf(cal.get(Calendar.MINUTE)); String segundo = String.valueOf(cal.get(Calendar.SECOND)).length() == 1 ? "0" + String.valueOf(cal.get(Calendar.SECOND)) : String.valueOf(cal.get(Calendar.SECOND)); try { if (DEBUG) { Utilidades.escribeLog("Generando PDFs -guardarPdf-"); } if (contimagen < 2) { pantbarra.barra.setMinimum(1); pantbarra.barra.setMaximum(2); } else { pantbarra.barra.setMinimum(1); pantbarra.barra.setMaximum(rutaboton.length); } pantbarra.barra.setValue(1); pantbarra.setTitle(pantbarra.getTitle()); pantbarra.validate(); String nombrefichero = "Documentacion.pdf"; String ruta = rutalote + separador + nombrefichero + ".pdf"; if (!textoFichero.getText().isEmpty()) { nombrefichero = textoFichero.getText() + ".pdf"; } if (!textoDirectorio.getText().isEmpty()) { ruta = textoDirectorio.getText(); ruta = ruta + separador + nombrefichero; } FileOutputStream ficheroPdf = new FileOutputStream(ruta); File filename = new File(rutaboton[0].toString()); java.awt.image.BufferedImage imagen = javax.imageio.ImageIO.read(filename); com.itextpdf.text.Image imagenpdf = com.itextpdf.text.Image.getInstance(imagen, null); pdfDocument.setPageSize(new Rectangle(imagenpdf.getWidth(), imagenpdf.getHeight())); PdfWriter writer = PdfWriter.getInstance(pdfDocument, ficheroPdf); writer.open(); pdfDocument.open(); pdfDocument.addHeader("IP", lote.substring(16, 19) + "." + lote.substring(19, 22) + "." + lote.substring(22, 25) + "." + lote.substring(25, 28)); pdfDocument.addHeader("fechadigita", lote.substring(6, 8) + "/" + lote.substring(4, 6) + "/" + lote.substring(0, 4) + " " + lote.substring(9, 11) + ":" + lote.substring(11, 13) + ":" + lote.substring(13, 15)); pdfDocument.addHeader("fechacreacion", dia + "/" + mes + "/" + anio + " " + hora + ":" + minuto + ":" + segundo); for (int i = 0; i < rutaboton.length; i++) { filename = new File(rutaboton[i].toString()); imagen = javax.imageio.ImageIO.read(filename); imagenpdf = com.itextpdf.text.Image.getInstance(imagen, null); // imagenpdf.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight()); // imagenpdf.setAlignment(com.itextpdf.text.Image.ALIGN_JUSTIFIED_ALL); // com.itextpdf.text.Image instance = com.itextpdf.text.Image.getInstance(imagenpdf); // pdfDocument.setPageSize(new com.itextpdf.text.Rectangle(PageSize.A4.getWidth(), PageSize.A4.getHeight())); pantbarra.barra.setValue(i); pantbarra.setTitle(titulo + " " + (i + 1) + " de " + rutaboton.length); pdfDocument.setPageSize(new Rectangle(imagenpdf.getWidth(), imagenpdf.getHeight())); // pdfDocument.add(instance); pdfDocument.add(imagenpdf); pdfDocument.newPage(); pantbarra.validate(); } pdfDocument.close(); writer.close(); } catch (Exception e) { Utilidades.escribeLog("Error Generando PDFs -guardarPdf- " + e.getMessage()); errorpdf = true; } pantbarra.dispose(); } }.start(); pantbarra.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); pantbarra.setVisible(false); pantbarra.setVisible(true); return !errorpdf; }
From source file:pdfcompressor.PDFCompressor.java
public void outputPDF(String pathToOutput) throws FileNotFoundException, DocumentException, BadElementException, IOException { com.itextpdf.text.Image itextImg; Document outDocument = new Document(); outDocument.setMargins(0f, 0f, 0f, 0f); PdfWriter writer = PdfWriter.getInstance(outDocument, new FileOutputStream(pathToOutput)); writer.setFullCompression();/*ww w . j a v a 2s . c o m*/ writer.open(); outDocument.open(); int progress = 0; for (java.awt.Image img : getBuffedImg()) { itextImg = Image.getInstance(getImageByteArray(img, compressRate)); itextImg.scaleToFit(595f, 842f); outDocument.add(itextImg); for (ProgressListener listener : saveListener) { listener.haveProgress(++progress, numOfPages); } } outDocument.close(); writer.close(); for (ProgressListener listener : saveListener) { listener.finished(); } }
From source file:pdfcompressor.PDFCompressor.java
public void getFileSize() throws DocumentException, IOException { com.itextpdf.text.Image itextImg; Document outDocument = new Document(); outDocument.setMargins(0f, 0f, 0f, 0f); ByteArrayOutputStream memoryOutput = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(outDocument, memoryOutput); writer.setFullCompression();/* w ww . j a va2 s . c o m*/ writer.open(); outDocument.open(); for (java.awt.Image img : getBuffedImg()) { itextImg = Image.getInstance(getImageByteArray(img, compressRate)); itextImg.scaleToFit(595f, 842f); outDocument.add(itextImg); } outDocument.close(); writer.close(); for (ProgressListener listener : sizeEstimateListener) { listener.finished(memoryOutput.toByteArray().length); } }
From source file:Presentacion.Consentimientos.java
/** * Mtodo que permite generar el informe con base en el archivo adjunto del consentimiento * @param evt /* w ww.j a va 2s . co m*/ */ private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed JFileChooser elegirCarpeta = new JFileChooser(); elegirCarpeta.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int o = elegirCarpeta.showOpenDialog(this); if (o == JFileChooser.APPROVE_OPTION) { String path = elegirCarpeta.getSelectedFile().getAbsolutePath(); String diaFecha = String.valueOf(FechaConsentimiento.getCalendar().get(Calendar.DAY_OF_MONTH)); String mesFecha = String.valueOf(FechaConsentimiento.getCalendar().get(Calendar.MONTH) + 1); String annoFecha = String.valueOf(FechaConsentimiento.getCalendar().get(Calendar.YEAR)); String fecha = diaFecha + "-" + mesFecha + "-" + annoFecha; try { File informe = new File(path + "\\Consentimiento N" + txtNConsentimiento.getText() + " " + jcPaciente.getSelectedItem() + " (" + fecha + ").pdf"); if (informe.exists()) { informe.delete(); } try { String imagen = path + "\\Consentimiento N" + txtNConsentimiento.getText() + " " + jcPaciente.getSelectedItem() + " (" + fecha + ").jpg"; File outputfile = new File(imagen); ImageIO.write((RenderedImage) OpConsentimientos.getAdjunto(), "jpg", outputfile); Document document = new Document(); FileOutputStream fos = new FileOutputStream(informe); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.open(); document.open(); com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(imagen); img.scalePercent(45); document.add(img); outputfile.delete(); document.close(); writer.close(); } catch (IOException | DocumentException ex) { Logger.getLogger(Consentimientos.class.getName()).log(Level.SEVERE, null, ex); } Desktop.getDesktop().open(informe); } catch (IOException ex) { Logger.getLogger(Consentimientos.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:Print.Print.java
private void printToPDF(BufferedImage bufferedImage) { // define pdfprinter and within try clause create for (int i = 0; i < quantity; i++) { PdfWriter writer = null; try {/* ww w . j av a2s . com*/ // define fileoutputstream and within try clause create FileOutputStream fos = null; document = new Document(PageSize.A4.rotate()); fos = new FileOutputStream(output + photoID + "-" + Integer.toString(i + 1) + ".pdf"); // create the writer object try { writer = PdfWriter.getInstance(document, fos); } catch (DocumentException ex) { System.out.println(ex.getMessage()); } // open the writer and the document and add the image into the document writer.open(); document.open(); try { PdfContentByte pdfCB = new PdfContentByte(writer); if (bufferedImage == null) { Image image = Image.getInstance(input); image.scaleToFit(640, 480); document.add(image); } else { Image image = Image.getInstance(pdfCB, bufferedImage, 1); image.scaleToFit(640, 480); document.add(Image.getInstance(image)); } } catch (DocumentException ex) { System.out.println(ex.getMessage()); } catch (IOException ex) { System.out.println(ex.getMessage()); } // close the document and writer document.close(); writer.close(); System.out.println("Printer done."); } catch (Exception e) { System.out.println(e.getMessage()); } } }
From source file:Print.Print.java
public void printIndex(ArrayList<String> imagesPath, String customer) { try {//from w ww.jav a 2 s .co m //ArrayList<Image> images = new ArrayList<Image>(); Map<Image, String> dict = new HashMap<Image, String>(); for (String path : imagesPath) { try { System.out.println("path = /home/student" + path); int index = path.lastIndexOf("/"); String photoId = path.substring(index + 1, path.length()); Image newImage = Image.getInstance("/home/student" + path); //images.add(newImage); dict.put(newImage, photoId); } catch (BadElementException ex) { Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Total images = " + dict.size()); Document index = new Document(PageSize.A4.rotate()); FileOutputStream fos = new FileOutputStream("/home/student/Pictures/index.pdf"); PdfWriter writer = PdfWriter.getInstance(index, fos); writer.open(); index.open(); PdfPTable adresTable = new PdfPTable(3); PdfPCell adresCell = new PdfPCell(new Paragraph(customer)); adresCell.setColspan(3); adresTable.addCell(adresCell); adresTable.setHorizontalAlignment(Element.ALIGN_CENTER); adresTable.setWidthPercentage(100); index.add(adresTable); PdfPTable table = new PdfPTable(imagesPath.size()); for (Map.Entry<Image, String> image : dict.entrySet()) { PdfPCell cell = new PdfPCell(); table.setHorizontalAlignment(Element.ALIGN_LEFT); table.setWidthPercentage(10); table.addCell(image.getValue()); cell.addElement(image.getKey()); table.addCell(cell); } index.add(table); //index.add(adresTable); index.close(); writer.close(); System.out.println("Index printed"); // // define pdfprinter and within try clause create // PdfWriter writer = null; // FileOutputStream fos = null; // Document index = new Document(PageSize.A4.rotate()); // File file; // try { // file = new File("/home/student/Pictures/index.pdf"); // if(!file.exists()){ // file.createNewFile(); // // } // String test = "test data"; // fos = new FileOutputStream(file); // fos.write(test.getBytes()); // fos.flush(); // } catch (FileNotFoundException ex) { // Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex); // } catch (IOException ex) { // Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex); // } // // for (BufferedImage image : bufferedImages) { // try { // writer = PdfWriter.getInstance(index, fos); // } catch (DocumentException ex) { // System.out.println(ex.getMessage()); // } // writer.open(); // index.open(); // try { // PdfContentByte pdfCB = new PdfContentByte(writer); // Image newImage = Image.getInstance(pdfCB, image, 1); // index.add(Image.getInstance(newImage)); // } catch (DocumentException ex) { // System.out.println(ex.getMessage()); // } catch (IOException ex) { // Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex); // } // } // index.close(); // writer.close(); // System.out.println("Index done."); } catch (DocumentException ex) { Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(Print.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:procuracoes.classes.Digitalizacao.java
public void salva(String user) throws MorenaException, SQLException { source = TwainManager.selectSource(null); npag = 0;/* w w w . j a v a2 s . c om*/ if (source != null) { morenaImage = new MorenaImage(source); //cria um objeto MorenaImage que manipula a imagem direta do scanner image = Toolkit.getDefaultToolkit().createImage(morenaImage); //cria um objeto Image para receber a imagem i.add(npag, image); bimg = new BufferedImage(morenaImage.getWidth(), //cria um bufferedImage para poder salvar a imagem morenaImage.getHeight(), BufferedImage.TYPE_INT_RGB); g = bimg.createGraphics();//cria um graphics2d para manipular a imagem do buffer g.drawImage(i.get(npag), 0, 0, null);//desenha o objeto Image no BufferedImage try { ImageIO.write(bimg, "jpg", new File("C:/temp/teste" + Integer.toString(npag) + ".jpg")); //Cria um novo arquivo jpg; s.add("C:/temp/teste" + Integer.toString(npag) + ".jpg"); //Se a pasta no existir, a converso no funciona; } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Erro ao salvar imagem " + ex); } //---------------------------------------// JFrame f = new JFrame(); f.setBounds(50, 200, 1500, 600); f.setTitle("Visualizador"); f.setMaximumSize(new Dimension(1500, 600)); f.setMinimumSize(new Dimension(1500, 600)); cx = 0; cy = 0; resizedImg = new BufferedImage(100, 150, BufferedImage.TYPE_INT_ARGB); g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(i.get(npag), 0, 0, 100, 150, null); g2.dispose(); x = new JLabel(new ImageIcon(resizedImg)); GridBagLayout grid = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); GridBagConstraints d = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; d.gridheight = 8; d.gridwidth = 3; c.ipadx = 10; c.ipady = 10; c.gridx = cx; c.gridy = cy; d.gridheight = 0; d.gridwidth = 3; d.fill = GridBagConstraints.VERTICAL; d.anchor = d.PAGE_END; d.gridy = 5; f.setLayout(grid); f.add(new JLabel("Deseja continuar escaniando?"), d); JButton j1 = new JButton("Sim"); j1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { morenaImage = new MorenaImage(source); //cria um objeto MorenaImage que manipula a imagem direta do scanner image = Toolkit.getDefaultToolkit().createImage(morenaImage); //cria um objeto Image para receber a imagem i.add(npag, image); bimg = new BufferedImage(morenaImage.getWidth(), //cria um bufferedImage para poder salvar a imagem morenaImage.getHeight(), BufferedImage.TYPE_INT_RGB); g = bimg.createGraphics(); //cria um graphics2d para manipular a imagem do buffer g.drawImage(i.get(npag), 0, 0, null); //desenha o objeto Image no BufferedImage try { ImageIO.write(bimg, "jpg", new File("C:/temp/teste" + Integer.toString(npag) + ".jpg")); //Cria um novo arquivo jpg; s.add("C:/temp/teste" + Integer.toString(npag) + ".jpg"); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Erro ao salvar imagem " + ex); } //--------------------------------------------// resizedImg = new BufferedImage(100, 150, BufferedImage.TYPE_INT_ARGB); g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(i.get(npag), 0, 0, 100, 150, null); g2.dispose(); if (npag < 8) { cx = npag; } else if (npag >= 24) { cx = npag - 24; cy = 3; } else if (npag >= 16) { cx = npag - 16; cy = 2; } else if (npag >= 8) { cx = npag - 8; cy = 1; } x = new JLabel(new ImageIcon(resizedImg)); c.gridx = cx; c.gridy = cy; f.add(x, c); f.validate(); //----------------------------------------------// npag++; } }); f.add(j1, d); JButton j2 = new JButton("Nao"); j2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Document document = new Document(); Rectangle r = new Rectangle(morenaImage.getWidth(), morenaImage.getHeight()); document.setPageSize(r); try { String output = getNovoCaminho(); FileOutputStream fos = new FileOutputStream(output); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.open(); document.open(); int j = 0; while (j < npag) { document.add(com.itextpdf.text.Image.getInstance(s.get(j))); j++; } document.close(); writer.close(); } catch (DocumentException | IOException | SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao criar arquivo pdf " + ex); } try { TwainManager.close(); InsereProc in; in = new InsereProc(user); in.setVisible(true); f.dispose(); } catch (SQLException | TwainException ex) { Logger.getLogger(Digitalizacao.class.getName()).log(Level.SEVERE, null, ex); } } }); f.add(j2, d); f.add(x, c); npag++; f.validate(); f.setVisible(true); f.toFront(); } else { JOptionPane.showMessageDialog(null, "Documneto nao encontrado !"); } }
From source file:qcas.InstructorDashboardController.java
/** * method to export the image to pdf format * @throws IOException//from w ww . j ava2s. c o m * @throws DocumentException */ @FXML public void exportToPdf() throws IOException, DocumentException { Document document = new Document(); String output = "Current" + time + ".pdf"; FileOutputStream fos = new FileOutputStream(output); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.open(); document.open(); WritableImage image = lineChartAnchorPaneBR.snapshot(new SnapshotParameters(), null); Image returnImage = pdfExport(image, document); document.add(returnImage); image = pieChartAnchorPane.snapshot(new SnapshotParameters(), null); returnImage = pdfExport(image, document); document.newPage(); document.add(returnImage); image = stackedBarAnchorPane.snapshot(new SnapshotParameters(), null); returnImage = pdfExport(image, document); document.newPage(); document.add(returnImage); image = lineChartAnchorPaneBR.snapshot(new SnapshotParameters(), null); returnImage = pdfExport(image, document); document.newPage(); document.add(returnImage); document.close(); writer.close(); pdfDownloadedLabel.setVisible(true); }
From source file:qcas.QuizResultsController.java
public void exportToPdf() throws IOException, DocumentException { String s = ""; for (int i = 0; i < this.userAnswers.size(); i++) { s += "Question ".toUpperCase() + (i + 1) + ": " + "\t Your Answer: ".toUpperCase() + this.userAnswers.get(i) + "\t Correct Answer: ".toUpperCase() + this.userAnswerCheck.get(i) + "\n\n"; }//from ww w . j a v a 2 s .c om WritableImage image = QuizResultsDashboardPane.snapshot(new SnapshotParameters(), null); File file = new File("Student Report.png"); ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file); Document document = new Document(); String input = "Student Report.png"; // .gif and .jpg are ok too! String output = "Student Report.pdf"; try { FileOutputStream fos = new FileOutputStream(output); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.open(); document.open(); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", byteOutput); com.itextpdf.text.Image graph; graph = com.itextpdf.text.Image.getInstance(byteOutput.toByteArray()); graph.scaleToFit(500, 500); document.add((com.itextpdf.text.Element) graph); Font f = new Font(FontFamily.TIMES_ROMAN, 10.0f, Font.UNDERLINE, BaseColor.BLACK); Paragraph p = new Paragraph(s, f); document.add(p); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); } QuizResultsDashboardPane.setVisible(true); }