List of usage examples for org.apache.pdfbox.pdmodel PDPage getMediaBox
public PDRectangle getMediaBox()
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 . ja va2s. com*/ */ @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:se.streamsource.streamflow.web.application.pdf.PdfDocument.java
License:Apache License
public void init() { try {// w w w .j av a 2 s. c o m 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);//from www .j a v a 2 s . c o m if (contentStream != null) { contentStream.endText(); //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 w w. jav a 2s.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:uk.ac.leeds.ccg.andyt.rdl.web.RDL_ParsePDF.java
/** * https://svn.apache.org/viewvc/pdfbox/trunk/examples/ Based on * https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintURLs.java?view=markup&pathrev=1703066 * * @param f//from www . ja v a 2 s . c o m * @param filter * @param fis * @return * @throws IOException * @throws TikaException * @throws SAXException */ public static ArrayList<String[]> parseForLinks(File f, String filter, FileInputStream fis) throws IOException, TikaException, SAXException { ArrayList<String[]> result; result = new ArrayList<String[]>(); PDDocument doc = PDDocument.load(f); int pageNum = 0; for (PDPage page : doc.getPages()) { pageNum++; // if (pageNum == 11) { //Degug test hack System.out.println("Parsing page " + pageNum); PDFTextStripperByArea stripper = new PDFTextStripperByArea(); List<PDAnnotation> annotations = page.getAnnotations(); //first setup text extraction regions for (int j = 0; j < annotations.size(); j++) { PDAnnotation annot = annotations.get(j); if (annot instanceof PDAnnotationLink) { PDAnnotationLink link = (PDAnnotationLink) annot; PDRectangle rect = link.getRectangle(); //need to reposition link rectangle to match text space float x = rect.getLowerLeftX(); float y = rect.getUpperRightY(); float width = rect.getWidth(); float height = rect.getHeight(); int rotation = page.getRotation(); if (rotation == 0) { PDRectangle pageSize = page.getMediaBox(); y = pageSize.getHeight() - y; } else if (rotation == 90) { //do nothing } //Rectangle2D.Float awtRect = new Rectangle2D.Float(x, y, width, height); // Rounding here could be a problem! Rectangle2D.Double awtRect = new Rectangle2D.Double(x, y, width, height); stripper.addRegion("" + j, awtRect); } } stripper.extractRegions(page); for (int j = 0; j < annotations.size(); j++) { PDAnnotation annot = annotations.get(j); if (annot instanceof PDAnnotationLink) { PDAnnotationLink link = (PDAnnotationLink) annot; PDAction action = link.getAction(); if (action == null) { System.out.println(link.getContents()); System.out.println(annot.getClass().getName()); System.out.println(annot.getAnnotationName()); //System.out.println(annot.getNormalAppearanceStream().toString()); System.out.println(annot.getContents()); System.out.println(annot.getSubtype()); } else { String urlText = stripper.getTextForRegion("" + j); if (action instanceof PDActionURI) { PDActionURI uri = (PDActionURI) action; String url; url = uri.getURI(); if (url.contains(filter)) { String[] partResult; partResult = new String[3]; partResult[0] = "Page " + pageNum; partResult[1] = "urlText " + urlText; partResult[2] = "URL " + uri.getURI(); System.out.println(partResult[0]); System.out.println(partResult[1]); System.out.println(partResult[2]); System.out.println("URL " + uri.getURI()); result.add(partResult); } else { System.out.println("URL " + uri.getURI()); } } else { System.out.println(action.getType()); } } } else { System.out.println(annot.getClass().getName()); System.out.println(annot.getAnnotationName()); System.out.println(annot.getContents()); System.out.println(annot.getSubtype()); } } //} } // PDDocument doc = PDDocument.load(f); // int pageNum = 0; // for (PDPage page : doc.getPages()) { // pageNum++; // List<PDAnnotation> annotations = page.getAnnotations(); // // for (PDAnnotation annotation : annotations) { // PDAnnotation annot = annotation; // if (annot instanceof PDAnnotationLink) { // PDAnnotationLink link = (PDAnnotationLink) annot; // PDAction action = link.getAction(); // if (action instanceof PDActionURI) { // PDActionURI uri = (PDActionURI) action; // String oldURI = uri.getURI(); // String name = annot.getAnnotationName(); // String contents = annot.getContents(); // PDAppearanceStream a = annot.getNormalAppearanceStream(); // //String newURI = "http://pdfbox.apache.org"; // System.out.println(oldURI + " " + name + " " + contents); // //uri.setURI(newURI); // } // } // } // } // result = parseWithTika(fis); //XMPSchema schema; //schema = new XMPSchema(); //List<String> XMPBagOrSeqList; //XMPBagOrSeqList = getXMPBagOrSeqList(XMPSchema schema, String name) { // PDDocument tPDDocument; // tPDDocument = PDDocument.load(f); // COSDocument tCOSDocument; // tCOSDocument = tPDDocument.getDocument(); // String header; // header = tCOSDocument.getHeaderString(); // System.out.println(header); // PDDocumentCatalog tPDDocumentCatalog; // tPDDocumentCatalog = tPDDocument.getDocumentCatalog(); // PDDocumentNameDictionary tPDDocumentNameDictionary; // tPDDocumentNameDictionary = tPDDocumentCatalog.getNames(); // COSDictionary tCOSDictionary; // tCOSDictionary = tPDDocumentNameDictionary.getCOSDictionary(); //tCOSDictionary. // PDPageNode tPDPageNode; // tPDPageNode = tPDDocumentCatalog.getPages(); // List<COSObject> tCOSObjects; // tCOSObjects = tCOSDocument.getObjects(); // int n; // n = tCOSObjects.size(); // System.out.println(n); // COSObject aCOSObject; // String s; // for (int i = 0; i < n; i++) { // aCOSObject = tCOSObjects.get(i); // s = aCOSObject.toString(); // System.out.println(s); // } // XMPMetadata tXMPMetadata; // tXMPMetadata = getXMPMetadata(tPDDocument); // Document XMPDocument; // XMPDocument = tXMPMetadata.getXMPDocument(); // Node n; // n = XMPDocument.getFirstChild(); // parseNode(n); return result; }