List of usage examples for org.apache.pdfbox.pdmodel PDDocument save
public void save(OutputStream output) throws IOException
From source file:so.rezervacija.StampajRezervaciju.java
@Override protected void izvrsiKonkretnuOperaciju() throws Exception { PDDocument doc = null; PDPage page = null;/* w w w.ja va2 s .co m*/ try { doc = new PDDocument(); page = new PDPage(); doc.addPage(page); PDFont pdfFont = PDType1Font.HELVETICA_BOLD; float fontSize = 25; float leading = 1.5f * fontSize; PDPageContentStream contentStream = new PDPageContentStream(doc, page); PDRectangle mediabox = page.findMediaBox(); float margin = 72; float width = mediabox.getWidth() - 2 * margin; float startX = mediabox.getLowerLeftX() + margin; float startY = mediabox.getUpperRightY() - margin; String text = "Izvrsili ste rezervaciju za tretman " + r.getTretman() + ", vreme rezervacije:" + new SimpleDateFormat("YYYY-MM-dd HH:mm").format(r.getVreme()) + " zaposleni koji ce vrsiti tretman:" + r.getZaposleni().getImePrezime(); List<String> lines = new ArrayList<String>(); int lastSpace = -1; while (text.length() > 0) { int spaceIndex = text.indexOf(' ', lastSpace + 1); if (spaceIndex < 0) { lines.add(text); text = ""; } else { String subString = text.substring(0, spaceIndex); float size = fontSize * pdfFont.getStringWidth(subString) / 1000; if (size > width) { if (lastSpace < 0) // So we have a word longer than the line... draw it anyways { lastSpace = spaceIndex; } subString = text.substring(0, lastSpace); lines.add(subString); text = text.substring(lastSpace).trim(); lastSpace = -1; } else { lastSpace = spaceIndex; } } } contentStream.beginText(); contentStream.setFont(pdfFont, fontSize); contentStream.moveTextPositionByAmount(startX, startY); for (String line : lines) { contentStream.drawString(line); contentStream.moveTextPositionByAmount(0, -leading); } contentStream.endText(); contentStream.close(); doc.save("PotvrdaRezervacije.pdf"); if (Desktop.isDesktopSupported()) { try { File myFile = new File("../ServerProjekat/PotvrdaRezervacije.pdf"); Desktop.getDesktop().open(myFile); } catch (IOException ex) { // no application registered for PDFs } } doc.close(); } catch (Exception e) { System.out.println(e); } }
From source file:src.controller.PageController.java
/** * Extrait la page spcifie du document et la sauvegade dans le fichier donn * @param document//www . j av a2 s. c om * @param id * @param filename */ public void extractPage(PDDocument document, int id, String filename) { try { PDDocument doc = new PDDocument(); if (document.getPage(id) != null) { doc.addPage(document.getPage(id)); } doc.save(filename + ".pdf"); doc.close(); System.out.println("La page " + id + " a bien t extraite."); } catch (Exception e) { System.out.println(e.toString()); } }
From source file:src.view.controller.MainController.java
public void testCreateFile() { try {/*from w ww .j a v a2 s . c o m*/ PDDocument document = new PDDocument(); document.save(TEST_DOC_TITLE + ".pdf"); document.close(); System.out.println(TRANSLATOR.getString("TEST_FILE_GENERATED")); } catch (IOException e) { System.out.println(e.toString()); } }
From source file:src.view.controller.MainController.java
public void testAddImage() { try {//from w ww . j ava 2 s . c om ImageController imageController = new ImageController(); // Chargement du document File file = new File(TEST_DOC_TITLE + ".pdf"); PDDocument document = PDDocument.load(file); document.addPage(new PDPage()); PDPageContentStream contentStream = new PDPageContentStream(document, document.getPage(document.getNumberOfPages() - 1), PDPageContentStream.AppendMode.APPEND, true); // Ajout d'une image sur la deuxime page imageController.addImage(document, contentStream, TEST_IMG_NAME, 100, 400, 0.2f); contentStream.close(); document.save(TEST_DOC_TITLE + ".pdf"); document.close(); System.out.println(TRANSLATOR.getString("TEST_IMAGE_ADDED")); } catch (IOException e) { System.out.println(e.toString()); } }
From source file:src.view.controller.MainController.java
public void testAddTable() { try {/* w ww.ja v a 2 s. c o m*/ TableController tableController = new TableController(); // Chargement du document File file = new File(TEST_DOC_TITLE + ".pdf"); PDDocument document = PDDocument.load(file); document.addPage(new PDPage()); PDPageContentStream contentStream = new PDPageContentStream(document, document.getPage(document.getNumberOfPages() - 1), PDPageContentStream.AppendMode.APPEND, true); // Instanciation d'un tableau Table table = new Table(100, 600, 200, 200); // Gnration du tableau table.generateTable(2, 7); table.addColumns(2); // Rcupration d'une cellule Cell cell = table.getCell(0); // Initialisation du contenu cell.setContent("TEST"); // Affichage du contenu dans la cellule tableController.printCellContent(contentStream, cell, "center", "middle"); // Ajout d'un tableau tableController.printTable(contentStream, table, false); contentStream.close(); document.save(TEST_DOC_TITLE + ".pdf"); System.out.println(TRANSLATOR.getString("TEST_TABLE_ADDED")); } catch (IOException e) { System.out.println(e.toString()); } }
From source file:stepReport.reports.model.savePDFModel.java
public void savePDFSemanal(File file, String[][] matrizDados) { if (matrizDados == null) return;/*from w w w .jav a 2 s .co m*/ //Cria o documento PDDocument document = new PDDocument(); //Vou criando as paginas dinamicamente de acordo com o numero de registros a serem impressos. //Para cada 25 registros, crio uma nova pagina //O valor de k vai ser atualizado durante o loop de impressao de registros, //assim como o loop de impressao de registro comeca a partir do valor de k int k = 1; int pagina = 0; while (k < matrizDados.length) { //Variavel com o numero da pagina pagina++; //Adiciona uma pagina PDPage page = new PDPage(); //Configura o padrao de tamanho da pagina page.setMediaBox(PDRectangle.A4); //Configura a orientacao page.setRotation(90); //Adiciona a pagina ao documento document.addPage(page); PDFont font; //Obtem a largura da pagina float pageWidth = page.getMediaBox().getWidth(); try { //abre o buffer pra edicao da pagina PDPageContentStream contentStream = new PDPageContentStream(document, page); //Gira a pagina em 90 graus contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0)); PDImageXObject pdImage = PDImageXObject.createFromFile("./step2.png", document); contentStream.drawImage(pdImage, 30, 520); //Define a cor da letra contentStream.setNonStrokingColor(Color.BLACK); //Abre pra edicao escrita contentStream.beginText(); //Configura a fonte de titulo e o tamanho no buffer font = PDType1Font.COURIER_BOLD; contentStream.setFont(font, 18); contentStream.setLeading(14.5f); contentStream.newLineAtOffset(250, 530); contentStream.showText("Resumo de Horas semanais"); //Imprime o numero da pagina font = PDType1Font.COURIER; contentStream.setFont(font, 12); contentStream.newLineAtOffset(490, 0); contentStream.showText("Pag " + Integer.toString(pagina)); //Define o ponto de partida em X e Y contentStream.newLineAtOffset(-700, -50); //Define a fonte do cabecalho font = PDType1Font.COURIER_BOLD; contentStream.setFont(font, 12); //carrega o cabecalho com nome, profissao, itera pra cada data da semana e depois o total String titulo = StringUtils.rightPad("Nome", 20) + StringUtils.rightPad("Profissao", 16); for (int i = 2; i < matrizDados[0].length; i++) titulo += matrizDados[0][i] + " "; //Escreve o cabecalho contentStream.showText(titulo); //Troca a fonte pra normal font = PDType1Font.COURIER; contentStream.setFont(font, 12); //TODO criar loop duplo para criar pagina e depois imprimir o dado enquanto houver dados a serem impressos contentStream.newLine(); //Para cada linha da matriz recebida, vou formatar os campos nome, profissao, cada data da semana e o total pra imprimir na linha //Tenho que comecar a partir de k porque pode nao ser a primeira pagina. //Configuro o limite baseado se eu estou ou nao na ultima pagina int limite = (k + savePDFModel.REGISTROS_PAGINA < matrizDados.length - 1) ? savePDFModel.REGISTROS_PAGINA : matrizDados.length - k; for (int i = 0; i < limite; i++) { String nome = this.formatName(matrizDados[i + k][0]); String profissao = this.formatProfissao(matrizDados[i + k][1]); String linha = nome + profissao; for (int j = 2; j < matrizDados[i].length; j++) linha += StringUtils.rightPad(matrizDados[i + k][j], 10); contentStream.showText(linha); contentStream.newLine(); } k += limite; //Imprime o total em negrito quando chega no final System.out.println(k); if (k >= matrizDados.length) { font = PDType1Font.COURIER_BOLD; contentStream.setFont(font, 12); Double[] totais = new Double[matrizDados[0].length - 2]; for (int i = 0; i < totais.length; i++) totais[i] = 0.0; for (int i = 1; i < matrizDados.length; i++) { for (int j = 2; j < matrizDados[i].length; j++) { if (!matrizDados[i][j].equals("")) totais[j - 2] += Double.parseDouble(matrizDados[i][j]); } } String linhaTot = StringUtils.rightPad("Totais", 36); for (int i = 0; i < totais.length; i++) { linhaTot += StringUtils.rightPad(totais[i].toString(), 10); } contentStream.showText(linhaTot); //Imprime a linha de assinatura this.signatureLine(contentStream); } contentStream.endText(); contentStream.close(); } catch (javax.imageio.IIOException ex) { JOptionPane.showMessageDialog(new JFrame(), "Imagem step2.png no encontrada"); return; } catch (IOException ex) { Logger.getLogger(savePDFModel.class.getName()).log(Level.SEVERE, null, ex); } } try { //Esse save vai dentro do loop? document.save(file); document.close(); } catch (IOException ex) { Logger.getLogger(savePDFModel.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:swp.bibjsf.renderer.Printer.java
License:Apache License
/** * Prints ID cards for all readers listed in <code>idcontent</code> as a PDF * file that is to be saved under given <code>filename</code>. * * @param idcontent data of readers whose ID card is to be printed * @param filename name of the PDF file to be created *//*www.j a v a2s . com*/ public void printCards(List<Content> idcontent, OutputStream outStream) { if (idcontent.isEmpty()) { return; } try { PDDocument document = createDocument(idcontent); // Save the results and ensure that the document is properly closed: try { document.save(outStream); } catch (COSVisitorException e) { e.printStackTrace(); } document.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:testppttopdf.TestPptToPdf.java
/** * @param args the command line arguments */// w w w.jav a 2 s . c o m public static void main(String[] args) throws FileNotFoundException, IOException, COSVisitorException { // TODO code application logic here FileInputStream is = new FileInputStream("/home/sagar/Desktop/Shareback/test.ppt"); HSLFSlideShow ppt = new HSLFSlideShow(is); is.close(); Dimension pgsize = ppt.getPageSize(); int idx = 1; for (HSLFSlide slide : ppt.getSlides()) { BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); // clear the drawing area graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); // render slide.draw(graphics); // save the output FileOutputStream out = new FileOutputStream("/home/sagar/Desktop/Shareback/img/slide-" + idx + ".jpg"); javax.imageio.ImageIO.write(img, "jpg", out); out.close(); idx++; } String someimg = "/home/sagar/Desktop/Shareback/img/"; PDDocument document = new PDDocument(); File file = new File(someimg); if (file.isDirectory()) { for (File f : file.listFiles()) { InputStream in = new FileInputStream(f); BufferedImage bimg = ImageIO.read(in); float width = bimg.getWidth(); float height = bimg.getHeight(); PDPage page = new PDPage(new PDRectangle(width + 10, height + 10)); document.addPage(page); PDXObjectImage img = new PDJpeg(document, new FileInputStream(f)); PDPageContentStream contentStream = new PDPageContentStream(document, page); contentStream.drawImage(img, 0, 0); contentStream.close(); in.close(); } document.save("/home/sagar/Desktop/Shareback/test-generated.pdf"); document.close(); } else { System.out.println(someimg + "is not a Directory"); } }
From source file:testppttopdf.TestPptToPdf.java
static void testPptxToPdf() { String filepath = "/home/sagar/Desktop/Shareback/test.pptx"; FileInputStream is;//w w w . j av a 2s. c o m try { is = new FileInputStream(filepath); XMLSlideShow pptx = new XMLSlideShow(is); Dimension pgsize = pptx.getPageSize(); int idx = 1; for (XSLFSlide slide : pptx.getSlides()) { BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); // clear the drawing area graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); // render slide.draw(graphics); // save the output FileOutputStream out = new FileOutputStream( "/home/sagar/Desktop/Shareback/img/slide-" + idx + ".jpg"); javax.imageio.ImageIO.write(img, "jpg", out); out.close(); idx++; } String someimg = "/home/sagar/Desktop/Shareback/pptx/img/"; PDDocument document = new PDDocument(); File file = new File(someimg); if (!file.exists()) file.mkdir(); if (file.isDirectory()) { for (File f : file.listFiles()) { InputStream in = new FileInputStream(f); BufferedImage bimg = ImageIO.read(in); float width = bimg.getWidth(); float height = bimg.getHeight(); PDPage page = new PDPage(new PDRectangle(width + 10, height + 10)); document.addPage(page); PDXObjectImage img = new PDJpeg(document, new FileInputStream(f)); PDPageContentStream contentStream = new PDPageContentStream(document, page); contentStream.drawImage(img, 0, 0); contentStream.close(); in.close(); } document.save("/home/sagar/Desktop/Shareback/test-generated-pptx.pdf"); document.close(); } else { System.out.println(someimg + "is not a Directory"); } } catch (Exception ex) { Logger.getLogger(TestPptToPdf.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Tools.PostProcessing.java
private String generateProcessedAndRejectPDFs(String preProcPdfFileName) throws IOException, COSVisitorException { PDDocument pdf = PDDocument.load(preProcPdfFileName); PDDocument rejectPdf = new PDDocument(); PDDocument cedmsPdf = new PDDocument(); //String rejectPdfFileName = preProcPdfFileName.replace(".pdf", "_forReject.pdf"); //String cedmsPdfFileName = preProcPdfFileName.replace(".pdf", "_forCEDMS.pdf"); int pageNum = pdf.getNumberOfPages(); //total number of pages in the pdf file // add reject page into rejectPdf PDFTextStripper pdfStripper = new PDFTextStripper(); int seqNumber = 1; boolean isLastReject = true; // last page status for (int i = 0; i < pageNum; i++) { PDPage page = (PDPage) pdf.getDocumentCatalog().getAllPages().get(i); int pageIndex = i + 1; pdfStripper.setStartPage(pageIndex); pdfStripper.setEndPage(pageIndex); String res = pdfStripper.getText(pdf); // System.out.println(res); if (res.contains(GlobalVar.PRE_PROC_KEY_SYMBOL)) { String[] data = GlobalVar.getCtrlNumAndfullSSN(res); String ctrlNum = data[0]; String fullSSN = data[1]; // System.out.println("full ssn:" + fullSSN + ". ctrl num:" + ctrlNum); // if(LEGIT_LV_MAP_FOR_COLOR_LV_LOG.containsKey(fullSSN)){ // // System.out.println("ctrl num: " + LEGIT_LV_MAP.get(fullSSN)); // } if (LEGIT_LV_MAP_FOR_COLOR_LV_LOG.containsKey(fullSSN) && LEGIT_LV_MAP_FOR_COLOR_LV_LOG.get(fullSSN).containsKey(ctrlNum)) { // System.out.println("Good leave"); int thisSeqNumber = Integer.parseInt(LEGIT_LV_MAP_FOR_COLOR_LV_LOG.get(fullSSN).get(ctrlNum)); if (thisSeqNumber == seqNumber) { cedmsPdf.addPage(page); //LEGIT_LV_MAP_FOR_COLOR_LV_LOG.get(fullSSN).remove(ctrlNum); // remove isLastReject = false; seqNumber++;// w w w. jav a 2 s .c om } else { String msg = "Order might be incorrect or there is a duplicate! ssn: " + fullSSN + " ctrl num: " + ctrlNum + ". Seq number is: " + seqNumber; //JOptionPane.showMessageDialog(null, msg); System.out.println(msg); } } else { rejectPdf.addPage(page); drawComments(rejectPdf, page, fullSSN, ctrlNum); isLastReject = true; } } else { // add the supporting documents to the last pdf file if (isLastReject) { rejectPdf.addPage(page); } else { cedmsPdf.addPage(page); } } } String cedmsPdfFileName = null; String rejectPdfFileName = null; if (preProcPdfFileName.contains(".pdf")) { cedmsPdfFileName = preProcPdfFileName.replace(".pdf", GlobalVar.PRE_CEDMS_PDF); rejectPdfFileName = preProcPdfFileName.replace(".pdf", "_forReject.pdf"); } else if (preProcPdfFileName.contains(".PDF")) { cedmsPdfFileName = preProcPdfFileName.replace(".PDF", GlobalVar.PRE_CEDMS_PDF); rejectPdfFileName = preProcPdfFileName.replace(".PDF", "_forReject.pdf"); } else { JOptionPane.showMessageDialog(null, "Invalid pre-processing file."); } // preProcPdfFileName.replace(".pdf", "_forReject.pdf"); // if (preProcPdfFileName.contains(".pdf")){ // cedmsPdfFileName = preProcPdfFileName.replace(".pdf", GlobalVar.PRE_CEDMS_PDF); // } else if (preProcPdfFileName.contains(".PDF")) { // cedmsPdfFileName = preProcPdfFileName.replace(".PDF", GlobalVar.PRE_CEDMS_PDF); // } else { // JOptionPane.showMessageDialog(null, "Invalid pre-processing file."); // } // if (rejectPdf.getNumberOfPages() > 0 && cedmsPdf.getNumberOfPages() > 0) { cedmsPdf.save(cedmsPdfFileName); rejectPdf.save(rejectPdfFileName); // JOptionPane.showMessageDialog(null, "The ready-for-upload and the rejected " // + "leave forms are saved in *_forCEDMS.pdf and *_forReject.pdf, respectively."); } else if (rejectPdf.getNumberOfPages() > 0) { rejectPdf.save(rejectPdfFileName); cedmsPdfFileName = null; // no cedms file is generated. // JOptionPane.showMessageDialog(null, "The rejected leave forms are saved in *_forReject.pdf."); } else if (cedmsPdf.getNumberOfPages() > 0) { cedmsPdf.save(cedmsPdfFileName); // JOptionPane.showMessageDialog(null, "The ready-for-upload leave forms are saved in *_forCEDMS.pdf."); } rejectPdf.close(); cedmsPdf.close(); pdf.close(); return cedmsPdfFileName; }