List of usage examples for org.apache.pdfbox.pdmodel PDPage setMediaBox
public void setMediaBox(PDRectangle mediaBox)
From source file:fi.nls.oskari.printout.printing.pdfbox.UsingTextMatrix.java
License:Apache License
/** * creates a sample document with some text using a text matrix. * //from w w w. j a v a 2s. co m * @param message * The message to write in the file. * @param outfile * The resulting PDF. * * @throws IOException * If there is an error writing the data. * @throws COSVisitorException * If there is an error writing the PDF. */ public void doIt(String message, String outfile) throws IOException, COSVisitorException { // the document PDDocument doc = null; try { doc = new PDDocument(); // Page 1 PDFont font = PDType1Font.HELVETICA; PDPage page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); float fontSize = 12.0f; PDRectangle pageSize = page.findMediaBox(); System.err.println("pageSize " + pageSize); System.err.println( "pageSize cm " + pageSize.getWidth() / 72 * 2.54 + "," + pageSize.getHeight() / 72 * 2.54); float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f; float stringWidth = font.getStringWidth(message); float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f; PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // counterclockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextRotation(i * Math.PI * 0.25, centeredXPosition, pageSize.getHeight() - centeredYPosition); contentStream.drawString(message + " " + i); } // clockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextRotation(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition); contentStream.drawString(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 2 page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // text scaling for (int i = 0; i < 10; i++) { contentStream.setTextScaling(12 + (i * 6), 12 + (i * 6), 100, 100 + i * 50); contentStream.drawString(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 3 page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); int i = 0; // text scaling combined with rotation contentStream.setTextMatrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.setTextMatrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5); contentStream.drawString(message + " " + i++); contentStream.endText(); contentStream.close(); // Page 4 { page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, false, false); contentStream.setFont(font, fontSize); contentStream.beginText(); AffineTransform root = new AffineTransform(); root.scale(72.0 / 2.54, 72.0 / 2.54); for (i = 0; i < pageSize.getHeight() / 72 * 2.54; i++) { // text scaling combined with rotation { AffineTransform rowMatrix = new AffineTransform(root); rowMatrix.translate(1, i); contentStream.setTextMatrix(rowMatrix); contentStream.drawString(message + " " + i); } } contentStream.endText(); contentStream.close(); } doc.save(outfile); } finally { if (doc != null) { doc.close(); } } }
From source file:org.qi4j.envisage.print.PDFWriter.java
License:Apache License
private void writeGraphPage(GraphDisplay graphDisplay) throws IOException { File tFile = File.createTempFile("envisage", "png"); graphDisplay.saveImage(new FileOutputStream(tFile), "png", 1d); BufferedImage img = ImageIO.read(tFile); int w = img.getWidth(); int h = img.getHeight(); int inset = 40; PDRectangle pdRect = new PDRectangle(w + inset, h + inset); PDPage page = new PDPage(); page.setMediaBox(pdRect); doc.addPage(page);/*from w w w . ja v a 2 s .co m*/ PDJpeg xImage = new PDJpeg(doc, img); PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.drawImage(xImage, (pdRect.getWidth() - w) / 2, (pdRect.getHeight() - h) / 2); contentStream.close(); }
From source file:org.sejda.impl.pdfbox.component.PDDocumentHandler.java
License:Apache License
/** * Import an existing page to the underlying {@link PDDocument} * /*from w ww . j a v a2 s .c o m*/ * @param page * @throws TaskIOException */ public void importPage(PDPage page) throws TaskIOException { PDPage imported; try { imported = document.importPage(page); } catch (IOException e) { throw new TaskIOException("An error occurred copying the page.", e); } imported.setCropBox(page.findCropBox()); imported.setMediaBox(page.findMediaBox()); imported.setResources(page.findResources()); imported.setRotation(page.findRotation()); }
From source file:org.socialbiz.cog.util.PDFUtil.java
License:Apache License
public static void main(String[] args) { //For test try {//www .java 2 s . co m String path = args[0]; PDDocument document = new PDDocument(); PDPage page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); document.addPage(page); PDFont font = PDType1Font.HELVETICA; PDPageContentStream contentStream = new PDPageContentStream(document, page, false, false); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, 800); String x = "hello world"; contentStream.drawString(x); contentStream.moveTextPositionByAmount(-90, -15); contentStream.setFont(font, 12); contentStream.drawString("Hello World3"); contentStream.endText(); contentStream.close(); document.save(path); document.close(); System.out.println("DONE.."); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.wso2.carbon.apimgt.impl.reportgen.ReportGenerator.java
License:Open Source License
/** * Generate PDF file for API microgateway request summary * * @param table object containing table headers and row data * @return InputStream pdf as a stream// w w w. j a va2s . co m * @throws IOException * @throws COSVisitorException */ public InputStream generateMGRequestSummeryPDF(TableData table) throws IOException, COSVisitorException { String[] columnHeaders = table.getColumnHeaders(); PDDocument document = new PDDocument(); PDPage page = new PDPage(); page.setMediaBox(PDPage.PAGE_SIZE_A4); page.setRotation(0); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page, false, false); // add logo InputStream in = APIManagerComponent.class.getResourceAsStream("/report/wso2-logo.jpg"); PDJpeg img = new PDJpeg(document, in); contentStream.drawImage(img, 375, 755); // Add topic contentStream.setFont(PDType1Font.HELVETICA_BOLD, 16); writeContent(contentStream, CELL_MARGIN, 770, "API Microgateway request summary"); // Add generated time contentStream.setFont(PDType1Font.HELVETICA_BOLD, FONT_SIZE); writeContent(contentStream, CELL_MARGIN, 730, "Report generated on: " + new Date().toString()); contentStream.setFont(TEXT_FONT, FONT_SIZE); // add table with data drowTableGrid(contentStream, table.getRows().size()); writeRowsContent(contentStream, columnHeaders, table.getRows()); // Add meta data // Whenever the summary report structure is updated this should be changed String requestCount = table.getRows().get(0).getEntries().get(2); document.getDocumentInformation().setCustomMetadataValue(MGW_META, getMetaCount(requestCount)); contentStream.close(); ByteArrayOutputStream out = new ByteArrayOutputStream(); document.save(out); document.close(); return new ByteArrayInputStream(out.toByteArray()); }
From source file:paper2ebook.Transformer.java
License:Apache License
/** * Output a PDF with as many pages as there are interesting areas in the * input document//from w w w.j a v a 2 s .c o m */ @Override public PDDocument extract() throws IOException { PDDocument extractedDocument = new PDDocument(); extractedDocument.setDocumentInformation(sourceDocument.getDocumentInformation()); extractedDocument.getDocumentCatalog() .setViewerPreferences(sourceDocument.getDocumentCatalog().getViewerPreferences()); @SuppressWarnings("unchecked") List<PDPage> pages = sourceDocument.getDocumentCatalog().getAllPages(); int pageCounter = 1; for (PDPage page : pages) { if (pageCounter >= startPage && pageCounter <= endPage) { List<PDRectangle> zoomedFragments = getFragments(page); for (PDRectangle fragment : zoomedFragments) { PDPage outputPage = extractedDocument.importPage(page); outputPage.setCropBox(fragment); outputPage.setMediaBox(page.getMediaBox()); outputPage.setResources(page.findResources()); outputPage.setRotation(page.findRotation()); // TODO: rotate the page in landscape mode is width > height } } pageCounter++; } return extractedDocument; }
From source file:pl.vane.pdf.factory.PDFFactory.java
License:Open Source License
public static PDDocument create(PDFDocument pdf) throws IOException { log.trace("--- pdf start"); PDDocument document = new PDDocument(); log.trace("--- load fonts"); Map<Integer, PDFont> fonts = loadFonts(pdf.getFont(), document); for (PDFPage data : pdf.getPage()) { // create page with size PDPage page = new PDPage(); PDFPageSize size = data.getSize(); PDRectangle mediaBox = new PDRectangle(size.getWidth(), size.getHeight()); page.setMediaBox(mediaBox); document.addPage(page);/*from www .j a v a 2 s . co m*/ // create content PDPageContentStream stream = new PDPageContentStream(document, page); for (PDFContent content : data.getContent()) { if (content instanceof PDFTextContent) { PDFTextContent txt = (PDFTextContent) content; PDFont font = fonts.get(txt.getFontId()); Point p = txt.getStart(); PDFWriter.drawString(stream, font, txt.getFontSize(), txt.getLeading(), p.getX(), p.getY(), txt.getText()); } } stream.close(); } log.trace("--- pdf end"); return document; }
From source file:se.streamsource.streamflow.web.application.pdf.PdfDocument.java
License:Apache License
public void init() { try {// w ww . j a v a2 s. c om pdf = new PDDocument(); PDPage page = new PDPage(); pdf.addPage(page); page.setMediaBox(pageSize); maxStringLength = page.getMediaBox().getWidth() - (leftMargin + rightMargin); contentStream = new PDPageContentStream(pdf, page); contentStream.beginText(); y = page.getMediaBox().getHeight() - headerMargin; contentStream.moveTextPositionByAmount(leftMargin, y); } catch (IOException e) { try { if (contentStream != null) { contentStream.close(); } } catch (IOException ioe) { contentStream = null; } throw new IllegalStateException(e.getMessage()); } }
From source file:se.streamsource.streamflow.web.application.pdf.PdfDocument.java
License:Apache License
private void pageBreakIfNeeded(PdfFont font) throws IOException { if (y - font.height < footerMargin) { PDPage newPage = new PDPage(); newPage.setMediaBox(pageSize); if (contentStream != null) { contentStream.endText();/*from w ww . jav a2s . co m*/ //Drawing all lines here after complete filling page if (this.pageLines.size() > 0) { for (ListIterator<LineObject> itr = pageLines.listIterator(); itr.hasNext();) { LineObject lineObject = itr.next(); this.line(lineObject.getEndX(), lineObject.getyPosition(), lineObject.getColor()); itr.remove(); } } contentStream.close(); } pdf.addPage(newPage); contentStream = new PDPageContentStream(pdf, newPage); y = newPage.getMediaBox().getHeight() - headerMargin - font.height; contentStream.beginText(); contentStream.moveTextPositionByAmount(leftMargin, y); } }
From source file:stepReport.reports.model.savePDFModel.java
public void savePDFSemanal(File file, String[][] matrizDados) { if (matrizDados == null) return;//from w ww. 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); } }