List of usage examples for org.apache.pdfbox.pdmodel PDDocument PDDocument
public PDDocument()
From source file:st.schoepfer.dicom2pdf.pdf.handler.PdfFileHandler.java
private void loadPDFFile() { // Laded die gewnschte Datei. // Wenn dabei ein Fehler auftritt wird ein neues Dokument mit einer leeren Seite geladen. try {//from www .j a v a2 s. co m this.aFile = PDDocument.load(this.FileName); } catch (Exception ex) { this.aFile = new PDDocument(); this.aFile.addPage(new PDPage()); } }
From source file:stepReport.reports.model.savePDFModel.java
public void savePDFSemanal(File file, String[][] matrizDados) { if (matrizDados == null) return;// w w w . j av a 2 s. c o 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
/** * Creates a PDF document containing the ID cards for <code>idcontent</code>. * * @param idcontent idcontent data of readers whose ID card is to be printed * @return PDF document containing the ID cards * @throws IOException thrown if document cannot be created *///from w w w .j a v a 2s . co m protected PDDocument createDocument(List<Content> idcontent) throws IOException { // Create a document and add a page to it PDDocument document = new PDDocument(); PDPage page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); document.addPage(page); int rowNumber = 0; int columnNumber = 0; // print numberOfCardsPerColumn x numberOfCardsPerRow cards per A4 page for (Content data : idcontent) { // System.out.println("IDCardPrinter.createDocument() " + columnNumber + " " + rowNumber); printCard(document, page, columnNumber, rowNumber, data); columnNumber++; if (columnNumber % numberOfCardsPerRow() == 0) { // start new row rowNumber++; columnNumber = 0; } if (rowNumber == numberOfCardsPerColumn()) { // start new page page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); document.addPage(page); rowNumber = 0; } } return document; }
From source file:testppttopdf.TestPptToPdf.java
/** * @param args the command line arguments *///from w w w . ja va 2s. 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 . jav a 2 s . 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++;//from w w w. j av a2 s. com } 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; }
From source file:uia.pdf.PDFMaker.java
License:Apache License
/** * Constructor.// w w w . j a v a2 s .com * @param font Font. * @throws IOException */ public PDFMaker(PDFont font) throws IOException { this.temp = new ArrayList<PDOutlineItem>(); this.doc = new PDDocument(); this.font = font; this.factory = new ValueParserFactory(); this.docOutline = new PDDocumentOutline(); this.doc.getDocumentCatalog().setDocumentOutline(this.docOutline); PDOutlineItem rootOI = new PDOutlineItem(); rootOI.setTitle("All"); this.docOutline.addLast(rootOI); this.hierarchyOI = new ArrayDeque<PDOutlineItem>(); this.hierarchyOI.push(rootOI); this.bookmarkPages = new ArrayList<BookmarkPage>(); }
From source file:uia.pdf.PDFMaker.java
License:Apache License
/** * Constructor./* w w w . j av a2 s . c o m*/ * @param fontFile TTF font file. * @throws IOException */ public PDFMaker(File fontFile) throws IOException { this.temp = new ArrayList<PDOutlineItem>(); this.doc = new PDDocument(); this.font = PDType0Font.load(this.doc, fontFile); this.factory = new ValueParserFactory(); this.docOutline = new PDDocumentOutline(); this.doc.getDocumentCatalog().setDocumentOutline(this.docOutline); PDOutlineItem rootOI = new PDOutlineItem(); rootOI.setTitle("All"); this.docOutline.addLast(rootOI); this.hierarchyOI = new ArrayDeque<PDOutlineItem>(); this.hierarchyOI.push(rootOI); this.bookmarkPages = new ArrayList<BookmarkPage>(); }
From source file:uia.pdf.PDFMakerTest.java
License:Apache License
@Test public void justTest() throws Exception { PDDocument doc = new PDDocument(); try {// w w w . j a v a 2 s. c o m PDPage page = new PDPage(); doc.addPage(page); PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, false, false); contents.moveTo(20, 650); contents.lineTo(500, 650); contents.stroke(); contents.close(); PDImageXObject pdImage = PDImageXObject .createFromFile(PDFMakerTest.class.getResource("sample.jpg").getFile(), doc); contents = new PDPageContentStream(doc, page, AppendMode.APPEND, false, false); contents.drawImage(pdImage, 20, 700); contents.close(); contents = new PDPageContentStream(doc, page, AppendMode.APPEND, false, false); contents.moveTo(20, 550); contents.lineTo(500, 550); contents.stroke(); contents.close(); doc.save("C:\\TEMP\\IMAGE.PDF"); } finally { doc.close(); } }
From source file:Utilities.BatchInDJMSHelper.java
public void generateProcessedAndRejectPDFs(String preProcPdfFileName) throws IOException, COSVisitorException { PDDocument pdf = PDDocument.load(preProcPdfFileName); PDDocument rejectPdf = new PDDocument(); PDDocument auditPdf = new PDDocument(); String rejectPdfFileName = preProcPdfFileName.replace(".pdf", "_forReject.pdf"); String auditPdfFileName = preProcPdfFileName.replace(".pdf", "_forAudit.pdf"); int pageNum = pdf.getNumberOfPages(); // add reject page into rejectPdf PDFTextStripper pdfStripper = new PDFTextStripper(); 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);//from ww w . j av a 2 s.c om 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.containsKey(fullSSN)) { System.out.println("ctrl num: " + LEGIT_LV_MAP.get(fullSSN)); } if (LEGIT_LV_MAP.containsKey(fullSSN) && LEGIT_LV_MAP.get(fullSSN).containsKey(ctrlNum)) { System.out.println("Good leave"); auditPdf.addPage(page); isLastReject = false; } 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 { auditPdf.addPage(page); } } } if (rejectPdf.getNumberOfPages() > 0 && auditPdf.getNumberOfPages() > 0) { auditPdf.save(auditPdfFileName); rejectPdf.save(rejectPdfFileName); JOptionPane.showMessageDialog(null, "The ready-for-aduit and the rejected leave forms are saved in *_forAudit.pdf and *_forReject.pdf, respectively."); numberPDFFile(auditPdfFileName); } else if (rejectPdf.getNumberOfPages() > 0) { rejectPdf.save(rejectPdfFileName); JOptionPane.showMessageDialog(null, "The rejected leave forms are saved in *_forReject.pdf."); } else if (auditPdf.getNumberOfPages() > 0) { auditPdf.save(auditPdfFileName); JOptionPane.showMessageDialog(null, "The ready-for-aduit leave forms are saved in *_forAduit.pdf."); numberPDFFile(auditPdfFileName); } rejectPdf.close(); auditPdf.close(); pdf.close(); }