List of usage examples for com.lowagie.text Document add
public boolean add(Element element) throws DocumentException
Element
to the Document
. From source file:de.dhbw.humbuch.util.PDFHandler.java
protected void addInformationAboutDocument(Document document, String informationText) { PdfPTable table = createMyStandardTable(1); new PDFHandler.TableBuilder(table, new String[] { informationText }) .font(FontFactory.getFont("Times New Roman", 14, Font.BOLD)).fillTable(); try {/*from w w w . j av a2 s. co m*/ document.add(table); PDFHandler.addEmptyLineToDocument(document, 1); } catch (DocumentException e) { e.printStackTrace(); } }
From source file:de.dhbw.humbuch.util.PDFHandler.java
protected static void addEmptyLineToDocument(Document document, int number) { Paragraph paragraph = new Paragraph(); for (int i = 0; i < number; i++) { paragraph.add(new Paragraph(" ")); }//from w ww .j a v a 2s .com try { document.add(paragraph); } catch (DocumentException e) { System.err.println("Could not add empty line to documnet " + e.getStackTrace()); } }
From source file:de.japes.text.PdfCreator.java
License:Open Source License
public String exportToPdf(byte[] imgArray) { String filename;//from w ww . j a v a 2s . co m Document document = new Document(); Image img = null; Calendar cal = Calendar.getInstance(); filename = "chart_" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH) + "_" + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE) + ".pdf"; try { img = Image.getInstance(imgArray); } catch (MalformedURLException e) { return e.getMessage(); } catch (IOException e) { return e.getMessage(); } catch (BadElementException e) { return e.getMessage(); } img.setAlignment(Image.ALIGN_CENTER); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileOutputStream(filename)); // step 3: we open the document document.open(); // step 4: we add a paragraph to the document document.add(img); } catch (DocumentException de) { return de.getMessage(); } catch (IOException ioe) { return ioe.getMessage(); } // step 5: we close the document document.close(); return filename; }
From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java
License:Open Source License
private Document writeDocument(Document document, List<SudokuData> sudokus) throws DocumentException { document.open();//from w w w . ja v a2 s . co m // TODO Von auen konfigurieren document.addAuthor("Jrgen Dufner"); document.addCreationDate(); document.addCreator("de.jdufner.sudoku.Generator"); document.addKeywords("Sudoku"); document.addTitle("Sudokus in unterschiedlichen Schwierigkeitsgraden"); document.add(writePdfMetaTable(sudokus)); document.close(); return document; }
From source file:de.jdufner.sudoku.generator.pdf.PdfPrinterImpl.java
License:Open Source License
private void writeFrontpage(String name, Document document, List<PdfSolution> solutions) throws DocumentException { document.open();/* w w w. ja v a 2s . c o m*/ Paragraph p = new Paragraph(name); p.setAlignment(Element.ALIGN_CENTER); p.setSpacingBefore(20f); p.setSpacingAfter(20f); document.add(p); PdfPTable table = new PdfPTable(17); table.setWidthPercentage(100); int[] width = { 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; table.setWidths(width); PdfPCell cell; table.addCell(buildHeaderCell("Name", 90, true, false)); table.addCell(buildHeaderCell("Schwierigkeitsgrad", 90, false, false)); table.addCell(buildHeaderCell("Besetzte Zellen", 90, false, false)); table.addCell(buildHeaderCell("Simple", 90, false, false)); table.addCell(buildHeaderCell("Hidden Single", 90, false, false)); table.addCell(buildHeaderCell("Naked Pair", 90, false, false)); table.addCell(buildHeaderCell("Naked Triple", 90, false, false)); table.addCell(buildHeaderCell("Naked Quad", 90, false, false)); table.addCell(buildHeaderCell("Hidden Pair", 90, false, false)); table.addCell(buildHeaderCell("Hidden Triple", 90, false, false)); table.addCell(buildHeaderCell("Hidden Quad", 90, false, false)); table.addCell(buildHeaderCell("Intersection Removal", 90, false, false)); table.addCell(buildHeaderCell("Y-Wing", 90, false, false)); table.addCell(buildHeaderCell("X-Wing", 90, false, false)); table.addCell(buildHeaderCell("Jellyfish", 90, false, false)); table.addCell(buildHeaderCell("Swordfish", 90, false, false)); table.addCell(buildHeaderCell("Backtracking", 90, false, true)); boolean even = false; for (PdfSolution solution : solutions) { table.addCell(buildBodyNumberCell(solution.getId(), even, true, false)); table.addCell(buildBodyTextCell(solution.getLevel().toString(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getFixed(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategySimple(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyHiddenSingle(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyNakedPair(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyNakedTriple(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyNakedQuad(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyHiddenPair(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyHiddenTriple(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyHiddenQuad(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyIntersectionRemoval(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyYwing(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyXwing(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyJellyfish(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategySwordfish(), even, false, false)); table.addCell(buildBodyNumberCell(solution.getStrategyBacktracking(), even, false, true)); even = (even ? false : true); } document.add(table); document.close(); }
From source file:de.maklerpoint.office.Schnittstellen.PDF.ExportListePDF.java
License:Open Source License
public void write() throws DocumentException, FileNotFoundException { SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm"); Document doc = null; if (titles.length > 7) doc = new Document(PageSize.A4.rotate(), 20, 20, 20, 20); else//from www . j a v a 2s . c om doc = new Document(PageSize.A4, 20, 20, 20, 20); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename)); doc.addAuthor("MaklerPoint - www.maklerpoint.de"); doc.addCreator("MaklerPoint - www.maklerpoint.de"); doc.addCreationDate(); doc.addTitle(title); doc.open(); doc.add(new Paragraph(title, FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, Color.BLACK))); Table t = new Table(titles.length, data.length + 1); t.setPadding(3); t.setSpacing(0); t.setBorderWidth(1); for (int i = 0; i < titles.length; i++) { Cell c1 = new Cell(titles[i]); c1.setHeader(true); t.addCell(c1); } t.endHeaders(); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { Cell c1 = null; if (data[i][j] != null) c1 = new Cell(data[i][j].toString()); else c1 = new Cell(""); t.addCell(c1); } } doc.add(t); if (footer == null) { doc.add(new Paragraph( ("Export " + title + " - Genereriert am " + df.format(new Date(System.currentTimeMillis()))) + " von MaklerPoint", FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black))); } else { doc.add(new Paragraph(footer, FontFactory.getFont(FontFactory.TIMES, 10, Font.NORMAL, Color.black))); } doc.close(); }
From source file:de.sub.goobi.forms.ProzessverwaltungForm.java
License:Open Source License
/** * Generate result as PDF.// w ww. j a v a 2 s .c o m */ public void generateResultAsPdf() { FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { /* * Vorbereiten der Header-Informationen */ HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); try { ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType("search.pdf"); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\""); ServletOutputStream out = response.getOutputStream(); SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses, this.showArchivedProjects); HSSFWorkbook wb = sr.getResult(); List<List<HSSFCell>> rowList = new ArrayList<>(); HSSFSheet mySheet = wb.getSheetAt(0); Iterator<Row> rowIter = mySheet.rowIterator(); while (rowIter.hasNext()) { HSSFRow myRow = (HSSFRow) rowIter.next(); Iterator<Cell> cellIter = myRow.cellIterator(); List<HSSFCell> row = new ArrayList<>(); while (cellIter.hasNext()) { HSSFCell myCell = (HSSFCell) cellIter.next(); row.add(myCell); } rowList.add(row); } Document document = new Document(); Rectangle a4quer = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth()); PdfWriter.getInstance(document, out); document.setPageSize(a4quer); document.open(); if (rowList.size() > 0) { Paragraph p = new Paragraph(rowList.get(0).get(0).toString()); document.add(p); PdfPTable table = new PdfPTable(9); table.setSpacingBefore(20); for (List<HSSFCell> row : rowList) { for (HSSFCell hssfCell : row) { // TODO aufhbschen und nicht toString() nutzen String stringCellValue = hssfCell.toString(); table.addCell(stringCellValue); } } document.add(table); } document.close(); out.flush(); facesContext.responseComplete(); } catch (Exception e) { logger.error(e); } } }
From source file:de.thorstenberger.examServer.webapp.action.SystemConfigSubmitAction.java
License:Open Source License
/** * @param mapping/* w ww. j ava2s .co m*/ * @param request * @param response * @param configManager * @return */ private ActionForward createSignedPDF(final ActionMapping mapping, final HttpServletRequest request, final HttpServletResponse response, final ConfigManager configManager) { final ActionErrors errors = new ActionErrors(); try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final Document pdf = new Document(); PdfWriter.getInstance(pdf, baos); pdf.open(); pdf.add(new Paragraph("Signaturtest.")); pdf.close(); final InputStream pdfIn = new ByteArrayInputStream(baos.toByteArray()); baos.reset(); SignPdf.signAndTimestamp(pdfIn, baos, configManager.getPDFSignatureInfos()); // write signed pdf to response response.setContentType("application/pdf"); // set an appropriate filename response.setHeader("Content-Disposition", "attachment; filename=signaturetest.pdf"); response.getOutputStream().write(baos.toByteArray()); return null; } catch (final DocumentException e) { addError(errors, e); } catch (final IOException e) { addError(errors, e); } catch (final SignatureException e) { addError(errors, e); } catch (final KeyStoreException e) { addError(errors, e); } saveMessages(request, errors); return mapping.findForward("success"); }
From source file:de.tr1.cooperator.manager.web.CreateSubscriberListAction.java
License:Open Source License
/** * This method is called by the struts-framework if the submit-button is pressed. * It creates a PDF-File and puts in into the output-stream of the response. *//*from w w w . j a v a 2 s. co m*/ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CreateSubscriberListForm myForm = (CreateSubscriberListForm) form; boolean bSortByName; if (myForm.getSortBy().equals(myForm.SORTBYPN)) bSortByName = false; else bSortByName = true; //create Collection for the results... Event eEvent = EventManager.getInstance().getEventByID(myForm.getEventID()); Collection cSubscriberList = UserManager.getInstance().getUsersByCollection(eEvent.getSubscriberList()); Collection cExamResults = EventResultManager.getInstance().getResults(eEvent.getID()); Iterator cSubscriberListIT = cSubscriberList.iterator(); Collection cSubscriberResultList = new ArrayList(); while (cSubscriberListIT.hasNext()) { User CurUser = (User) cSubscriberListIT.next(); String UserPNR = CurUser.getPersonalNumber(); Iterator cExamResultsIT = cExamResults.iterator(); ExamResult curExamResult = null; String ResultUserPNR = null; while (cExamResultsIT.hasNext()) { curExamResult = (ExamResult) cExamResultsIT.next(); ResultUserPNR = curExamResult.getUserPersonalNumber(); if (UserPNR.equals(ResultUserPNR)) break; } if (UserPNR.equals(ResultUserPNR)) { if (bSortByName) { UserResultSortByName URS = new UserResultSortByName(CurUser, "" + curExamResult.getResult()); cSubscriberResultList.add(URS); } else { UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "" + curExamResult.getResult()); cSubscriberResultList.add(URS); } } else { if (bSortByName) { UserResultSortByName URS = new UserResultSortByName(CurUser, "-"); cSubscriberResultList.add(URS); } else { UserResultSortByPersonalNumber URS = new UserResultSortByPersonalNumber(CurUser, "-"); cSubscriberResultList.add(URS); } } } //sort List Collections.sort((List) cSubscriberResultList); BaseFont bf; //36pt = 0.5inch Document document = new Document(PageSize.A4, 36, 36, 72, 72); try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); } catch (Exception e) { Log.addLog("CreateSubscriberListAction: Error creating BaseFont: " + e); //2do: add ErrorMessage and return to inputFormular! return mapping.findForward("GeneralFailure"); } //calculate the number of cols and their width int cols = 0; ArrayList alWidth = new ArrayList(); float boldItalicFactor = 1.2f; if (myForm.getShowNumber()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NUMBER, TABLEHEADER_FONTSIZE))); if (myForm.getShowPersonalNumber()) alWidth.add(new Float( boldItalicFactor * bf.getWidthPoint(TABLEHEADER_PERSONALNUMBER, TABLEHEADER_FONTSIZE))); if (myForm.getShowName()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_NAME, TABLEHEADER_FONTSIZE))); if (myForm.getShowEmail()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_EMAIL, TABLEHEADER_FONTSIZE))); if (myForm.getShowResult()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_RESULT, TABLEHEADER_FONTSIZE))); if (myForm.getAddInfoField()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_INFO, TABLEHEADER_FONTSIZE))); if (myForm.getAddSignField()) alWidth.add(new Float(boldItalicFactor * bf.getWidthPoint(TABLEHEADER_SIGN, TABLEHEADER_FONTSIZE))); cols = alWidth.size(); float totalWidth = 0; //calculate the whole length Iterator alIterator = alWidth.iterator(); for (; alIterator.hasNext(); totalWidth += ((Float) alIterator.next()).floatValue()) ; //calculate relativ width for the table float[] width = new float[cols]; alIterator = alWidth.iterator(); int i = 0; while (alIterator.hasNext()) { float pixLength = ((Float) alIterator.next()).floatValue(); //alWidthRelativ.add( new Float( pixLength/totalWidth ) ); width[i] = pixLength / totalWidth; i++; } //needed for the shrink (enlarge?) float shrinkFactor; try { //1st: set correct outputstream PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); //1.5st: set content-stuff response.setContentType("application/pdf"); //2nd: set EventManager for PageEvents to Helper writer.setPageEvent( new CreateSubscriberListActionHelper(myForm.getHeaderLeft(), myForm.getHeaderRight())); //3rd: open document for editing the content document.open(); //4th: add content Phrase pInfoText = new Phrase(myForm.getInfoText(), new Font(bf, 12, Font.BOLD)); document.add(pInfoText); //PdfPTable( cols ) PdfPTable table = new PdfPTable(width); float documentWidth = document.right() - document.left(); if (documentWidth < totalWidth) { table.setTotalWidth(documentWidth); shrinkFactor = documentWidth / totalWidth; } else { table.setTotalWidth(totalWidth); shrinkFactor = 1; } table.setLockedWidth(true); Font headerFont = new Font(bf, TABLEHEADER_FONTSIZE * shrinkFactor, Font.BOLDITALIC); Font cellFont = new Font(bf, TABLECELL_FONTSIZE * shrinkFactor, Font.NORMAL); if (myForm.getShowNumber()) table.addCell(new Phrase(TABLEHEADER_NUMBER, headerFont)); if (myForm.getShowPersonalNumber()) table.addCell(new Phrase(TABLEHEADER_PERSONALNUMBER, headerFont)); if (myForm.getShowName()) table.addCell(new Phrase(TABLEHEADER_NAME, headerFont)); if (myForm.getShowEmail()) table.addCell(new Phrase(TABLEHEADER_EMAIL, headerFont)); if (myForm.getShowResult()) table.addCell(new Phrase(TABLEHEADER_RESULT, headerFont)); if (myForm.getAddInfoField()) table.addCell(new Phrase(TABLEHEADER_INFO, headerFont)); if (myForm.getAddSignField()) table.addCell(new Phrase(TABLEHEADER_SIGN, headerFont)); //fill table Iterator iSRL = cSubscriberResultList.iterator(); int counter = 1; while (iSRL.hasNext()) { UserResult curResult = (UserResult) iSRL.next(); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); if (myForm.getShowNumber()) table.addCell(new Phrase("" + counter++, cellFont)); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); if (myForm.getShowPersonalNumber()) table.addCell(new Phrase(curResult.getPersonalNumber(), cellFont)); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); if (myForm.getShowName()) table.addCell(new Phrase(curResult.getSurname() + ", " + curResult.getFirstName(), cellFont)); if (myForm.getShowEmail()) table.addCell(new Phrase(curResult.getEmailAddress(), cellFont)); if (myForm.getShowResult()) table.addCell(new Phrase(curResult.getResult(), cellFont)); if (myForm.getAddInfoField()) table.addCell(new Phrase("", cellFont)); if (myForm.getAddSignField()) table.addCell(new Phrase("", cellFont)); } //set how many rows are header... table.setHeaderRows(1); document.add(table); //5th: close document, write the output to the stream... document.close(); } catch (Exception de) { Log.addLog("CreateSubscriberListAction: Error creating PDF: " + de); } //we dont need to return a forward, because we write directly to the outputstream! return null; }
From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java
License:Apache License
/****************************************************************************************************** * Adds the all pages.//w ww. ja va 2 s . c o m * * @param pagesizemode {@link PdfPageSize} * @param writer {@link PdfWriter} * @param pdfdoc {@link Document} * @return {@link PdfPageLabels} * * * @throws ImageInterpreterException the image interpreter exception * @throws IOException Signals that an I/O exception has occurred. * @throws MalformedURLException the malformed url exception * @throws PDFManagerException the PDF manager exception * @throws ImageManagerException *******************************************************************************************************/ private PdfPageLabels addAllPages(PdfPageSize pagesizemode, PdfWriter writer, Document pdfdoc, Watermark myWatermark) throws ImageInterpreterException, IOException, MalformedURLException, PDFManagerException, ImageManagerException { PdfPageLabels pagelabels = new PdfPageLabels(); int pageadded = 0; // sort the HashMap by the KeySet (pagenumber) Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(imageURLs); float scalefactor = 1; // scaling factor of the image int page_w = PaperSize.A4.width; int page_h = PaperSize.A4.height; LOGGER.debug("iterate over " + imageURLs.size() + " pages."); for (Integer imageKey : sortedMap.keySet()) { Watermark watermark = myWatermark; Image pdfImage = null; // PDF-Image LOGGER.debug("Writing page " + imageKey); boolean errorPage = false; // true if the image does not exists URL errorUrl = null; // url of the image that does not exists // ------------------------------------------------------------------------------------------------ // Title page available. Render it in pdftitlepage // ------------------------------------------------------------------------------------------------ if ((pdftitlepages != null) && (pdftitlepages.get(imageKey) != null)) { // title page PDFTitlePage pdftitlepage = pdftitlepages.get(imageKey); // create new PDF page try { pdfdoc.setPageSize(PageSize.A4); pdfdoc.setMargins(pdftitlepage.getLeftMargin(), pdftitlepage.getRightMargin(), pdftitlepage.getTopMargin(), pdftitlepage.getBottomMargin()); pageadded++; pdfdoc.newPage(); // create new page // set page name pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "-"); } catch (Exception e1) { throw new PDFManagerException("PDFManagerException occured while creating new page in PDF", e1); } // render title page pdftitlepage.render(pdfdoc); } // ------------------------------------------------------------------------------------------------ // Process image with imageKey // ------------------------------------------------------------------------------------------------ UrlImage pdfpage = imageURLs.get(imageKey); if (pdfpage.getURL() != null) { boolean added = false; boolean scaled = false; URL url = pdfpage.getURL(); // pdf hack if (ContentServerConfiguration.getInstance().getUsePdf()) { LOGGER.debug("trying to find original pdf"); PdfContentByte pdfcb = null; PdfReader pdfreader = null; PdfImportedPage importpage = null; try { String pdfpath = ContentServerConfiguration.getInstance().getRepositoryPathPdf() .replace("file:///", ""); LOGGER.debug("looking in " + pdfpath + " for pdf file"); String tiffPath = ContentServerConfiguration.getInstance().getRepositoryPathImages() .replace("file:///", ""); // String urlString = url.toString(); int pageNumber = pdfpage.getPageNumber(); // UrlImage copy = new PDFPage(pdfpage); URL pdfurl = new URL(url.toString().replace(tiffPath, pdfpath) .replace(url.toString().substring(url.toString().lastIndexOf(".")), ".pdf")); LOGGER.debug("pdfurl = " + pdfurl); if (new File(pdfurl.toURI()).exists()) { LOGGER.debug("found pdf " + pdfurl.toURI()); // copy.setURL(pdfurl); pdfcb = writer.getDirectContent(); pdfreader = new PdfReader(pdfurl); importpage = writer.getImportedPage(pdfreader, pageNumber); LOGGER.debug("creating orig pdf page"); Rectangle rect = pdfreader.getPageSize(pageNumber); try { pdfdoc.setPageSize(rect); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } pageadded++; pdfcb.addTemplate(importpage, 0, 0); added = true; LOGGER.debug("page:" + imageKey + " url: " + pdfurl.toString()); } } catch (URISyntaxException e) { LOGGER.debug(e); added = false; } finally { if (writer != null) { writer.freeReader(pdfreader); writer.flush(); } if (pdfreader != null) { pdfreader.close(); } } } if (!added) { // image file LOGGER.debug("using image to create pdf page"); // try to get ImageInterpreter from url ImageInterpreter myInterpreter = ImageFileFormat.getInterpreter(url, httpproxyhost, httpproxyport, httpproxyuser, httpproxypassword); try { // check preferred compression type depending on color depth Embedd preferredEmbeddingType = Embedd.ORIGBYTESTREAM; if (myInterpreter.getColordepth() == 1) { // bitonal image preferredEmbeddingType = embeddBitonalImage; } else if ((myInterpreter.getColordepth() > 1) && (myInterpreter.getSamplesperpixel() == 1)) { // greyscale image preferredEmbeddingType = embeddGreyscaleImage; } else { // color image preferredEmbeddingType = embeddColorImage; } // ------------------------------------------------------------------------------------- // Try to generate image // ------------------------------------------------------------------------------------- pdfImage = generatePdfImageFromInterpreter(myInterpreter, preferredEmbeddingType, errorPage, watermark, errorUrl); // ------------------------------------------------------------------------------------- // image couldn't be embedded yet (emergencyCase) // ------------------------------------------------------------------------------------- if (pdfImage == null) { LOGGER.warn( "Couldn't use preferred method for embedding the image. Instead had to use JPEG or RenderedImage"); // Get Interpreter and rendered Image // --------------------------------------------------------------------------------------------------------------------------------- RenderedImage ri = null; if (preferredEmbeddingType == embeddBitonalImage) { ImageManager sourcemanager = new ImageManager(url); boolean watermarkscale = ContentServerConfiguration.getInstance() .getScaleWatermark(); // should we scale // the watermark ? ri = sourcemanager.scaleImageByPixel(3000, 0, ImageManager.SCALE_BY_WIDTH, 0, null, null, watermark, watermarkscale, ImageManager.BOTTOM); myInterpreter = sourcemanager.getMyInterpreter(); } else { ri = myInterpreter.getRenderedImage(); if (watermark != null) { ri = addwatermark(ri, watermark, 2); myInterpreter.setHeight( myInterpreter.getHeight() + watermark.getRenderedImage().getHeight()); } } // scale rendered image // --------------------------------------------------------------------------------------------------------------------------------- // float scalefactorX = 1; // float scalefactorY = 1; // switch (pagesizemode) { // case ORIGINAL: // scalefactorX = 72f / myInterpreter.getXResolution(); // scalefactorY = 72f / myInterpreter.getYResolution(); // break; // default: // /* // * check, if the image needs to be scaled, because // * it's bigger than A4 calculate the new scalefactor // */ // float page_w_pixel = (float) (page_w * // myInterpreter.getXResolution() / 25.4); // float page_h_pixel = (float) (page_h * // myInterpreter.getYResolution() / 25.4); // // float res_x = myInterpreter.getXResolution(); // float res_y = myInterpreter.getYResolution(); // // long w = myInterpreter.getWidth(); // get height and // // width // long h = myInterpreter.getHeight(); // // if ((w > page_w_pixel) || (h > page_h_pixel)) { // LOGGER.debug("scale image to fit the page"); // float scalefactor_w = page_w_pixel / w; // float scalefactor_h = page_h_pixel / h; // if (scalefactor_h < scalefactor_w) { // scalefactor = scalefactor_h; // } else { // scalefactor = scalefactor_w; // } // w = (long) (w * scalefactor); // h = (long) (h * scalefactor); // } // scalefactorX = (72f / res_x) * scalefactor; // scalefactorY = (72f / res_y) * scalefactor; // break; // } // //scalefactorX = 0.2f; // //scalefactorY = 0.2f; // if (preferredEmbeddingType == embeddBitonalImage) { // ImageManager sourcemanager = new ImageManager(url); // ri = sourcemanager.scaleImageByPixel((int) // (scalefactorX*100), (int) (scalefactorY*100), // ImageManager.SCALE_BY_PERCENT, 0, null, null, // watermark, true, ImageManager.BOTTOM); // }else{ // ri = ImageManipulator.scaleInterpolationBilinear(ri, // scalefactorX, scalefactorY); // } // myInterpreter.setHeight(ri.getHeight()); // myInterpreter.setWidth(ri.getWidth()); // scaled = true; // add Watermark // --------------------------------------------------------------------------------------------------------------------------------- // ri = addwatermark(ri, watermark, // ImageManager.BOTTOM); // myInterpreter.setHeight(myInterpreter.getHeight() + // watermark.getRenderedImage().getHeight()); // Try to write into pdfImage // --------------------------------------------------------------------------------------------------------------------------------- if (myInterpreter.getColordepth() > 1) { // compress image if greyscale or color ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream(); // JpegInterpreter jpint = new JpegInterpreter(ri); // jpint.setXResolution(myInterpreter.getXResolution()); // jpint.setYResolution(myInterpreter.getYResolution()); // jpint.writeToStream(null, bytesoutputstream); LOGGER.error("WritingJPEGImage"); writeJpegFromRenderedImageToStream(bytesoutputstream, ri, null, myInterpreter); byte[] returnbyteArray = bytesoutputstream.toByteArray(); if (bytesoutputstream != null) { bytesoutputstream.flush(); bytesoutputstream.close(); } pdfImage = Image.getInstance(returnbyteArray); returnbyteArray = null; } else { // its bitonal, but can't be embedded directly, // need to go via RenderedImage BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri); pdfImage = Image.getInstance(buffImage, null, false); if (myWatermark != null) { // create Image for Watermark JpegInterpreter jpint = new JpegInterpreter(myWatermark.getRenderedImage()); ByteArrayOutputStream bytesoutputstream = new ByteArrayOutputStream(); jpint.setXResolution(myInterpreter.getXResolution()); jpint.setYResolution(myInterpreter.getYResolution()); jpint.writeToStream(null, bytesoutputstream); byte[] returnbyteArray = bytesoutputstream.toByteArray(); jpint.clear(); if (bytesoutputstream != null) { bytesoutputstream.flush(); bytesoutputstream.close(); } Image blaImage = Image.getInstance(returnbyteArray); returnbyteArray = null; // set Watermark as Footer at fixed position // (200,200) Chunk c = new Chunk(blaImage, 200, 200); Phrase p = new Phrase(c); HeaderFooter hf = new HeaderFooter(p, false); pdfdoc.setFooter(hf); } // pdfdoc.setPageSize(arg0) // TODO das scheint nicht zu funktionieren... sollte // dieser Code entfernt werden? } } // end of : if (pdfImage == null) { } catch (BadElementException e) { throw new PDFManagerException("Can't create a PDFImage from a Buffered Image.", e); } catch (ImageManipulatorException e) { LOGGER.warn(e); } // --------------------------------------------------------------------------------------------------------- // place the image on the page // --------------------------------------------------------------------------------------------------------- if (pagesizemode == PdfPageSize.ORIGINAL) { // calculate the image width and height in points, create // the rectangle in points Rectangle rect = null; if (!scaled) { float image_w_points = (myInterpreter.getWidth() / myInterpreter.getXResolution()) * 72; float image_h_points = ((myInterpreter.getHeight()) / myInterpreter.getYResolution()) * 72; rect = new Rectangle(image_w_points, image_h_points); } else { rect = new Rectangle(myInterpreter.getWidth(), myInterpreter.getHeight()); } // create the pdf page according to this rectangle LOGGER.debug("creating original page sized PDF page:" + rect.getWidth() + " x " + rect.getHeight()); pdfdoc.setPageSize(rect); // create new page to put the content try { pageadded++; pdfdoc.newPage(); } catch (Exception e1) { throw new PDFManagerException( "DocumentException occured while creating page " + pageadded + " in PDF", e1); } // scale image and place it on page; scaling the image does // not scale the images bytestream if (!scaled) { pdfImage.scalePercent((72f / myInterpreter.getXResolution() * 100), (72f / myInterpreter.getYResolution() * 100)); } pdfImage.setAbsolutePosition(0, 0); // set image to lower // left corner boolean result; try { result = pdfdoc.add(pdfImage); // add it to PDF if (!result) { throw new PDFManagerException("Image \"" + url.toString() + "\" can's be added to PDF! Error during placing image on page"); } } catch (DocumentException e) { throw new PDFManagerException("DocumentException occured while adding the image to PDF", e); } } else { /* * it is not the original page size PDF will contain only A4 pages */ LOGGER.debug("creating A4 pdf page"); // create new page to put the content try { pageadded++; pdfdoc.setPageSize(PageSize.A4); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } float page_w_pixel = (float) (page_w * myInterpreter.getXResolution() / 25.4); float page_h_pixel = (float) (page_h * myInterpreter.getYResolution() / 25.4); float res_x = myInterpreter.getXResolution(); float res_y = myInterpreter.getYResolution(); long w = myInterpreter.getWidth(); // get height and width long h = myInterpreter.getHeight(); /* * if the page is landscape, we have to rotate the page; this is only done in PDF, the orig image bytestream is NOT rotated */ if (w > h) { LOGGER.debug("rotate image"); // must be rotated pdfImage.setRotationDegrees(90); // change width and height long dummy = w; w = h; h = dummy; // change the resolutions x and y float dummy2 = res_x; res_x = res_y; res_y = dummy2; } /* * check, if the image needs to be scaled, because it's bigger than A4 calculate the new scalefactor */ if ((w > page_w_pixel) || (h > page_h_pixel)) { LOGGER.debug("scale image to fit the page"); float scalefactor_w = page_w_pixel / w; float scalefactor_h = page_h_pixel / h; if (scalefactor_h < scalefactor_w) { scalefactor = scalefactor_h; } else { scalefactor = scalefactor_w; } w = (long) (w * scalefactor); h = (long) (h * scalefactor); } if (!scaled) { pdfImage.scalePercent((72f / res_x * 100) * scalefactor, (72f / res_y * 100) * scalefactor); } // center the image on the page // --------------------------------------------------------------- float y_offset = 0; // y - offset // get image size in cm; height float h_cm = (float) (h / (res_x / 2.54)); // float w_cm = (float) (w / (res_y / 2.54)); // and width if ((h_cm + 2) < (page_h / 10)) { y_offset = 2 * 72f / 2.54f; } float freespace_x = ((page_w_pixel - w) / res_x * 72f); float freespace_y = ((page_h_pixel - h) / res_y * 72f) - (y_offset); // set position add image pdfImage.setAbsolutePosition(freespace_x / 2, freespace_y); boolean result; try { result = pdfdoc.add(pdfImage); } catch (DocumentException e) { LOGGER.error(e); throw new PDFManagerException("DocumentException occured while adding the image to PDF", e); } if (!result) { // placing the image in the PDF was not successful throw new PDFManagerException("Image \"" + url.toString() + "\" can's be added to PDF! Error during placing image on page"); } // draw box around the image page // ------------------------------------------------------------------------------------------------ if (pagesizemode == PdfPageSize.A4BOX) { LOGGER.debug("draw box around the image page"); // draw a black frame around the image PdfContentByte pcb = writer.getDirectContent(); // calculate upper left corner of the box (measurment is // in points) float left_x = (freespace_x / 2); float left_y = freespace_y; // calculate the lower right corner of the box // (measurement is in points) float image_w_points = (w / res_x) * 72; float image_h_points = (h / res_y) * 72; pcb.setLineWidth(1f); pcb.stroke(); pcb.rectangle(left_x, left_y, image_w_points, image_h_points); pcb.stroke(); } } // end of: if (pagesizemode == PdfPageSize.ORIGINAL) { pdfImage = null; myInterpreter.clear(); // writer.freeReader(new PdfReader(pdfpage.getURL())); } // end of : if (pdfpage.getURL() != null) { // ------------------------------------------------------------------------------------------------ // it is a page from a PDF file which should be inserted // ------------------------------------------------------------------------------------------------ else if (pdfpage.getClass() == PDFPage.class && ((PDFPage) pdfpage).getPdfreader() != null) { PdfContentByte pdfcb = writer.getDirectContent(); PdfReader pdfreader = ((PDFPage) pdfpage).getPdfreader(); PdfImportedPage importpage = writer.getImportedPage(pdfreader, pdfpage.getPageNumber()); if (pagesizemode == PdfPageSize.ORIGINAL) { LOGGER.debug("creating orig pdf page"); Rectangle rect = pdfreader.getPageSize(pdfpage.getPageNumber()); try { pdfdoc.setPageSize(rect); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } // add content pageadded++; pdfcb.addTemplate(importpage, 0, 0); } else { LOGGER.debug("creating A4 pdf page"); try { pdfdoc.setPageSize(PageSize.A4); pdfdoc.newPage(); // create new page } catch (Exception e1) { throw new PDFManagerException("Exception occured while creating new page in PDF", e1); } // add content pageadded++; pdfcb.addTemplate(importpage, 0, 0); // draw box // if (pagesizemode == PdfPageSize.A4BOX) { // FIXME: nichts implementiert ? // } } } // handle pagename if (imageNames != null) { String pagename = imageNames.get(imageKey); if (pagename != null) { pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, pagename); } else { pagelabels.addPageLabel(pageadded, PdfPageLabels.EMPTY, "unnumbered"); } } // handle bookmarks and set destinator for bookmarks LOGGER.debug("handle bookmark(s) for page"); PdfDestination destinator = new PdfDestination(PdfDestination.FIT); setBookmarksForPage(writer, destinator, imageKey); // the key in the writer.flush(); // mashMap is the pagenumber } // end of while iterator over all pages } return pagelabels; }