List of usage examples for com.lowagie.text.pdf PdfContentByte setFontAndSize
public void setFontAndSize(BaseFont bf, float size)
From source file:is.idega.idegaweb.egov.printing.business.DocumentBusinessBean.java
License:Open Source License
public void createHeaderDate(Document document, PdfWriter writer, String dateString) throws DocumentException { /*/*from w w w . j av a2 s . c om*/ * final PdfPTable header = new PdfPTable(new float[]{1}); header.setWidthPercentage(100f); final PdfPCell defaultCell = header.getDefaultCell(); * defaultCell.setBorder(0); //defaultCell.setFixedHeight(getPointsFromMM(40)); defaultCell.setPadding(0); defaultCell.setNoWrap(true); * defaultCell.setVerticalAlignment(align); header.addCell(new Phrase(new Chunk(dateString, getDefaultParagraphFont()))); document.add(header); */ PdfContentByte cb = writer.getDirectContent(); cb.beginText(); Font font = getDefaultParagraphFont(); try { BaseFont bf = BaseFont.createFont(font.getFamilyname(), BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.setFontAndSize(bf, font.size()); // we show some text starting on some absolute position with a given // alignment cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, dateString, getPointsFromMM(210 - 20), getPointsFromMM(297 - 20), 0); cb.endText(); } catch (IOException e) { e.printStackTrace(); } }
From source file:managedbean.aas.reportController.java
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) { Document document = new Document(); try {//from ww w .jav a 2s .c o m List<InputStream> pdfs = streamOfPDFFiles; List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); // Code for pagination. if (paginate) { cb.beginText(); cb.setFontAndSize(bf, 9); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + currentPageNumber + " of " + totalPages, 520, 5, 0); cb.endText(); } } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } }
From source file:mx.randalf.digital.ocr.hocrtopdf.HocrToPdf.java
License:Open Source License
public void hocrToPdf(File fImg, File fHtml, File fPdf) throws IOException, DocumentException, Exception { URL inputHOCRFile = null;//from w ww. j a va 2s.c o m FileOutputStream outputPDFStream = null; // The resolution of a PDF file (using iText) is 72pt per inch float pointsPerInch = 72.0f; Source source = null; StartTag pageTag = null; Pattern imagePattern = null; Matcher imageMatcher = null; // Load the image Image pageImage = null; float dotsPerPointX; float dotsPerPointY; float pageImagePixelHeight; Document pdfDocument = null; PdfWriter pdfWriter = null; Font defaultFont = null; PdfContentByte cb = null; Pattern bboxPattern = null; Pattern bboxCoordinatePattern = null; StartTag ocrLineTag = null; try { try { inputHOCRFile = new URL("file://" + fHtml.getAbsolutePath()); } catch (MalformedURLException e) { throw e; } try { outputPDFStream = new FileOutputStream(fPdf); } catch (FileNotFoundException e) { throw e; } // Using the jericho library to parse the HTML file source = new Source(inputHOCRFile); // Find the tag of class ocr_page in order to load the scanned image pageTag = source.findNextStartTag(0, "class", "ocr_page", false); imagePattern = Pattern.compile("image\\s+([^;]+)"); imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title")); if (!imageMatcher.find()) { throw new Exception("Could not find a tag of class \"ocr_page\", aborting."); } try { pageImage = Image.getInstance(new URL("file://" + fImg.getAbsolutePath())); } catch (MalformedURLException e) { throw e; } dotsPerPointX = pageImage.getDpiX() / pointsPerInch; dotsPerPointY = pageImage.getDpiY() / pointsPerInch; pageImagePixelHeight = pageImage.getHeight(); pdfDocument = new Document( new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY)); pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream); pdfDocument.open(); // first define a standard font for our text defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK); // Put the text behind the picture (reverse for debugging) cb = pdfWriter.getDirectContentUnder(); //PdfContentByte cb = pdfWriter.getDirectContent(); pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY); pageImage.setAbsolutePosition(0, 0); // Put the image in front of the text (reverse for debugging) pdfWriter.getDirectContent().addImage(pageImage); //pdfWriter.getDirectContentUnder().addImage(pageImage); // In order to place text behind the recognised text snippets we are interested in the bbox property bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}"); // This pattern separates the coordinates of the bbox property bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)"); // Only tags of the ocr_line class are interesting ocrLineTag = source.findNextStartTag(0, "class", "ocr_line", false); while (ocrLineTag != null) { au.id.jericho.lib.html.Element lineElement = ocrLineTag.getElement(); Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title")); if (bboxMatcher.find()) { // We found a tag of the ocr_line class containing a bbox property Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group()); bboxCoordinateMatcher.find(); int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))), Integer.parseInt((bboxCoordinateMatcher.group(2))), Integer.parseInt((bboxCoordinateMatcher.group(3))), Integer.parseInt((bboxCoordinateMatcher.group(4))) }; String line = lineElement.getContent().extractText(); // float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX; float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY; // Put the text into the PDF cb.beginText(); // Comment the next line to debug the PDF output (visible Text) cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); // TODO: Scale the text width to fit the OCR bbox cb.setFontAndSize(defaultFont.getBaseFont(), Math.round(bboxHeightPt)); cb.moveText((float) (coordinates[0] / dotsPerPointX), (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY)); cb.showText(line); cb.endText(); } ocrLineTag = source.findNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false); } } catch (NumberFormatException e) { throw e; } catch (MalformedURLException e) { throw e; } catch (FileNotFoundException e) { throw e; } catch (BadElementException e) { throw e; } catch (IOException e) { throw e; } catch (DocumentException e) { throw e; } catch (Exception e) { throw e; } finally { if (pdfDocument != null) { pdfDocument.close(); } if (outputPDFStream != null) { outputPDFStream.close(); } } }
From source file:net.mitnet.tools.pdf.book.pdf.builder.PdfBookBuilder.java
License:Open Source License
public void buildBook(List<File> inputFileList, File outputFile) { try {/*from w ww . j av a 2s.c om*/ float pageWidth = getConfig().getPageWidth(); float pageHeight = getConfig().getPageHeight(); // Create new Document /* float marginLeft = 36; float marginRight = 36; float marginTop = 36; float marginBottom = 36; */ if (isVerboseEnabled()) { verbose("Building output PDF file " + outputFile); } // TableOfContents toc = new TableOfContents(); ProgressMonitor progressMonitor = getConfig().getProgressMonitor(); TocRowChangeListener tocRowChangeListener = getConfig().getTocRowChangeListener(); Document outputDocument = new Document(getConfig().getPageSize()); // Document outputDocument = new Document( getPageSize(), marginLeft, marginRight, marginTop, marginBottom ); PdfWriter pdfWriter = PdfWriter.getInstance(outputDocument, new FileOutputStream(outputFile)); // TODO - review PDF page event forwarder PdfPageEventLogger pdfPageEventLogger = new PdfPageEventLogger(); pdfWriter.setPageEvent(pdfPageEventLogger); outputDocument.open(); String metaTitle = getConfig().getMetaTitle(); if (!StringUtils.isEmpty(metaTitle)) { outputDocument.addTitle(metaTitle); } String metaAuthor = getConfig().getMetaAuthor(); if (!StringUtils.isEmpty(metaAuthor)) { outputDocument.addAuthor(metaAuthor); } PdfContentByte pdfContent = pdfWriter.getDirectContent(); // Loop through and pull pages int outputPageCount = 0; int currentSourceFileIndex = 0; int maxSourceFileIndex = inputFileList.size(); // BaseFont pageLabelFont = BaseFont.createFont( PdfBookBuilderConfig.DEFAULT_FONT, BaseFont.CP1250, BaseFont.EMBEDDED ); BaseFont pageLabelFont = BaseFont.createFont(PdfBookBuilderConfig.DEFAULT_FONT_PATH, BaseFont.CP1250, BaseFont.EMBEDDED); if (isVerboseEnabled()) { verbose("Using page label font " + pageLabelFont); } if (isVerboseEnabled()) { verbose("Assembling pages using n-up " + getConfig().getNup()); } for (File sourceFile : inputFileList) { currentSourceFileIndex++; // TODO - refactor current file PDF page processing to another method // TODO - handle failover to ensure processing continues ??? if (sourceFile.isFile()) { if (isVerboseEnabled()) { verbose("Reading source PDF file " + sourceFile); } int sourcePageIndex = 0; PdfReader sourcePdfReader = new PdfReader(sourceFile.getCanonicalPath()); PdfReaderHelper sourcePdfReaderHelper = new PdfReaderHelper(sourcePdfReader); if (isVerboseEnabled()) { verbose("PDF reader is " + sourcePdfReader); verbose("PDF reader helper is " + sourcePdfReaderHelper); } String currentSourcePdfTitle = FilenameUtils.getBaseName(sourceFile.getName()); String currentSourcePdfAuthor = getSystemUserName(); if (isVerboseEnabled()) { verbose("PDF title is " + currentSourcePdfTitle); verbose("PDF author is " + currentSourcePdfAuthor); } currentSourcePdfTitle = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfTitle); currentSourcePdfAuthor = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfAuthor); if (isVerboseEnabled()) { verbose("PDF info title is " + currentSourcePdfTitle); verbose("PDF info author is " + currentSourcePdfAuthor); } boolean firstPageOfCurrentSource = true; int maxSourcePages = sourcePdfReader.getNumberOfPages(); if (isVerboseEnabled()) { verbose("There are " + maxSourcePages + " page(s) in source PDF file " + sourceFile); } // process all pages from source doc while (sourcePageIndex < maxSourcePages) { // add new page to current document outputDocument.newPage(); outputPageCount++; if (isVerboseEnabled()) { verbose("Building output PDF page " + outputPageCount + " ..."); } // add first page of current source to TOC listener if (firstPageOfCurrentSource) { int currentPageIndex = outputPageCount; if (tocRowChangeListener != null) { TocRow tocEntry = new TocRow(currentSourcePdfTitle, currentPageIndex); tocRowChangeListener.addTocRow(tocEntry); if (isVerboseEnabled()) { verbose("Added TOC entry " + tocEntry + " to listener"); } } firstPageOfCurrentSource = false; } // extract first page from source document sourcePageIndex++; if (isVerboseEnabled()) { verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages + " from source to output"); } PdfImportedPage page1 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex); // n-up is 1 if (config.getNup() == 1) { // add first page to top half of current page // TODO - review magic transformation matrix numbers and offsets // TODO - calculate scaling/transform based on page rect and template rect float p1a = 0.65f; float p1b = 0; float p1c = 0; float p1d = 0.65f; float p1e = 20; float p1f = 160; pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f); // n-up is 2 (default) } else { // add first page to top half of current page // TODO - review magic transformation matrix numbers and offsets float p1a = 0.5f; float p1b = 0; float p1c = 0; float p1d = 0.5f; float p1e = (125); float p1f = ((pageWidth / 2) + 120 + 20); pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f); // extract second page from source document ? PdfImportedPage page2 = null; if (sourcePageIndex < maxSourcePages) { sourcePageIndex++; if (isVerboseEnabled()) { verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages + " from source to output"); } page2 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex); } // add second page to bottom half of current page if (page2 != null) { // TODO - review magic transformation matrix numbers and offsets float p2a = 0.5f; float p2b = 0; float p2c = 0; float p2d = 0.5f; float p2e = 125; float p2f = 120; pdfContent.addTemplate(page2, p2a, p2b, p2c, p2d, p2e, p2f); } } /* // add first page to top half of current page // TODO - review magic transformation matrix numbers and offsets float p1a = 0.5f; float p1b = 0; float p1c = 0; float p1d = 0.5f; float p1e = (125); float p1f = ((pageWidth / 2) + 120 + 20); pdfContent.addTemplate( page1, p1a, p1b, p1c, p1d, p1e, p1f ); // add second page to bottom half of current page if (page2 != null) { // TODO - review magic transformation matrix numbers and offsets float p2a = 0.5f; float p2b = 0; float p2c = 0; float p2d = 0.5f; float p2e = 125; float p2f = 120; pdfContent.addTemplate( page2, p2a, p2b, p2c, p2d, p2e, p2f ); } */ // Add current page number to page footer String pageCountLabel = "Page " + outputPageCount; pdfContent.beginText(); pdfContent.setFontAndSize(pageLabelFont, PdfBookBuilderConfig.DEFAULT_FONT_SIZE); pdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, pageCountLabel, (pageWidth / 2), 40, 0); pdfContent.endText(); } if (isVerboseEnabled()) { verbose("Finished reading " + maxSourcePages + " page(s) from source PDF file " + sourceFile); } // update progress if (isVerboseEnabled()) { if (progressMonitor != null) { int fileProgressPercentage = MathHelper.calculatePercentage(currentSourceFileIndex, maxSourceFileIndex); progressMonitor.setProgressPercentage(fileProgressPercentage); } } } } // close document outputDocument.close(); if (isVerboseEnabled()) { verbose("Output PDF file " + outputFile + " contains " + outputPageCount + " page(s)"); } // TODO - output ODT page stats summary } catch (Exception e) { String msg = "Error building PDF book: " + e.getMessage(); e.printStackTrace(System.err); System.err.println(msg); } }
From source file:net.sf.jasperreports.engine.export.PdfGlyphGraphics2D.java
License:Open Source License
@Override public void drawGlyphVector(GlyphVector glyphVector, float x, float y) { Font awtFont = glyphVector.getFont(); Map<Attribute, Object> fontAttrs = new HashMap<Attribute, Object>(); Map<TextAttribute, ?> awtFontAttributes = awtFont.getAttributes(); fontAttrs.putAll(awtFontAttributes); //the following relies on FontInfo.getFontInfo matching the face/font name com.lowagie.text.Font currentFont = pdfExporter.getFont(fontAttrs, locale, false); boolean bold = (currentFont.getStyle() & com.lowagie.text.Font.BOLD) != 0; boolean italic = (currentFont.getStyle() & com.lowagie.text.Font.ITALIC) != 0; PdfContentByte text = pdfContentByte.getDuplicate(); text.beginText();// w w w . jav a 2 s .com float[] originalCoords = new float[] { x, y }; float[] transformedCoors = new float[2]; getTransform().transform(originalCoords, 0, transformedCoors, 0, 1); text.setTextMatrix(1, 0, italic ? ITALIC_ANGLE : 0f, 1, transformedCoors[0], pdfExporter.getCurrentPageFormat().getPageHeight() - transformedCoors[1]); double scaleX = awtFont.getTransform().getScaleX(); double scaleY = awtFont.getTransform().getScaleY(); double minScale = Math.min(scaleX, scaleY); text.setFontAndSize(currentFont.getBaseFont(), (float) (minScale * awtFont.getSize2D())); if (bold) { text.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); text.setLineWidth(currentFont.getSize() * BOLD_STRIKE_FACTOR); text.setColorStroke(getColor()); } text.setColorFill(getColor()); //FIXME find a way to determine the characters that correspond to this glyph vector // so that we can map the font glyphs that do not directly map to a character text.showText(glyphVector); text.resetRGBColorFill(); if (bold) { text.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL); text.setLineWidth(1f); text.resetRGBColorStroke(); } text.endText(); pdfContentByte.add(text); }
From source file:org.caisi.tickler.web.TicklerPrinter.java
License:Open Source License
public void footer() { PdfContentByte cb = writer.getDirectContent(); cb.saveState();/*from w w w. ja v a 2 s . c o m*/ Date now = new Date(); String promoTxt = OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"); if (promoTxt == null) { promoTxt = new String(); } String strFooter = promoTxt + " " + formatter.format(now); float textBase = document.bottom(); cb.beginText(); cb.setFontAndSize(font.getBaseFont(), FONTSIZE); Rectangle page = document.getPageSize(); float width = page.getWidth(); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 20, 0); strFooter = "-" + writer.getPageNumber() + "-"; cb.showTextAligned(PdfContentByte.ALIGN_CENTER, strFooter, (width / 2.0f), textBase - 10, 0); cb.endText(); cb.restoreState(); }
From source file:org.eclipse.birt.report.engine.layout.pdf.font.FontCacheUtils.java
License:Open Source License
static void createUnicodePDF(String format, Locale locale, String fileName) throws Exception { FontMappingManager manager = FontMappingManagerFactory.getInstance().getFontMappingManager(format, locale); // step 1: creation of a document-object Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open();/* w w w.j a va2 s.com*/ for (int seg = 0; seg < 0xFF; seg++) { PdfContentByte cb = writer.getDirectContent(); cb.beginText(); for (int hi = 0; hi < 16; hi++) { for (int lo = 0; lo < 16; lo++) { int x = 100 + hi * 32; int y = 100 + lo * 32; char ch = (char) (seg * 0xFF + hi * 16 + lo); String fontFamily = manager.getDefaultPhysicalFont(ch); BaseFont bf = manager.createFont(fontFamily, Font.NORMAL); cb.setFontAndSize(bf, 16); cb.setTextMatrix(x, y); cb.showText(new String(new char[] { ch })); } } cb.endText(); } document.close(); }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void stampText(int pageCount, PdfPageData currentPageData, final StampTextToPDFPages stampText) { File tempFile = null;/*from ww w. ja va 2s.c om*/ try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToEdit = stampText.getPages(); if (pgsToEdit == null) return; List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); final PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile)); for (int page = 1; page <= pageCount; page++) { if (pagesToEdit.contains(new Integer(page))) { String chosenText = stampText.getText(); if (!chosenText.equals("")) { String chosenFont = stampText.getFontName(); Color chosenFontColor = stampText.getFontColor(); int chosenFontSize = stampText.getFontSize(); int chosenRotation = stampText.getRotation(); String chosenPlacement = stampText.getPlacement(); String chosenHorizontalPosition = stampText.getHorizontalPosition(); String chosenVerticalPosition = stampText.getVerticalPosition(); float chosenHorizontalOffset = stampText.getHorizontalOffset(); float chosenVerticalOffset = stampText.getVerticalOffset(); BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false); PdfContentByte cb; if (chosenPlacement.equals("Overlay")) cb = stamp.getOverContent(page); else cb = stamp.getUnderContent(page); cb.beginText(); cb.setColorFill(chosenFontColor); cb.setFontAndSize(font, chosenFontSize); int currentRotation = currentPageData.getRotation(page); Rectangle pageSize; if (currentRotation == 90 || currentRotation == 270) pageSize = reader.getPageSize(page).rotate(); else pageSize = reader.getPageSize(page); float startx; float starty; if (chosenVerticalPosition.equals("From the top")) { starty = pageSize.height(); } else if (chosenVerticalPosition.equals("Centered")) { starty = pageSize.height() / 2; } else { starty = 0; } if (chosenHorizontalPosition.equals("From the left")) { startx = 0; } else if (chosenHorizontalPosition.equals("Centered")) { startx = pageSize.width() / 2; } else { startx = pageSize.width(); } cb.showTextAligned(Element.ALIGN_CENTER, chosenText, startx + chosenHorizontalOffset, starty + chosenVerticalOffset, chosenRotation); cb.endText(); } } } stamp.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java
License:Open Source License
public void addHeaderFooter(int pageCount, PdfPageData currentPageData, final AddHeaderFooterToPDFPages addHeaderFooter) { File tempFile = null;// w w w . j ava2 s .co m try { tempFile = File.createTempFile("temp", null); ObjectStore.copy(selectedFile, tempFile.getAbsolutePath()); } catch (Exception e) { return; } try { int[] pgsToEdit = addHeaderFooter.getPages(); if (pgsToEdit == null) return; List pagesToEdit = new ArrayList(); for (int i = 0; i < pgsToEdit.length; i++) pagesToEdit.add(new Integer(pgsToEdit[i])); final PdfReader reader = new PdfReader(tempFile.getAbsolutePath()); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile)); String chosenFont = addHeaderFooter.getFontName(); Color chosenFontColor = addHeaderFooter.getFontColor(); int chosenFontSize = addHeaderFooter.getFontSize(); float chosenLeftRightMargin = addHeaderFooter.getLeftRightMargin(); float chosenTopBottomMargin = addHeaderFooter.getTopBottomMargin(); String text[] = new String[6]; text[0] = addHeaderFooter.getLeftHeader(); text[1] = addHeaderFooter.getCenterHeader(); text[2] = addHeaderFooter.getRightHeader(); text[3] = addHeaderFooter.getLeftFooter(); text[4] = addHeaderFooter.getCenterFooter(); text[5] = addHeaderFooter.getRightFooter(); Date date = new Date(); String shortDate = DateFormat.getDateInstance(DateFormat.SHORT).format(date); String longDate = DateFormat.getDateInstance(DateFormat.LONG).format(date); SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss a"); String time12 = formatter.format(date); formatter = new SimpleDateFormat("HH.mm.ss"); String time24 = formatter.format(date); String fileName = new File(selectedFile).getName(); BaseFont font = BaseFont.createFont(chosenFont, BaseFont.WINANSI, false); for (int page = 1; page <= pageCount; page++) { if (pagesToEdit.contains(new Integer(page))) { String[] textCopy = new String[text.length]; System.arraycopy(text, 0, textCopy, 0, text.length); for (int i = 0; i < 6; i++) { textCopy[i] = textCopy[i].replaceAll("<d>", shortDate); textCopy[i] = textCopy[i].replaceAll("<D>", longDate); textCopy[i] = textCopy[i].replaceAll("<t>", time12); textCopy[i] = textCopy[i].replaceAll("<T>", time24); textCopy[i] = textCopy[i].replaceAll("<f>", fileName); textCopy[i] = textCopy[i].replaceAll("<F>", selectedFile); textCopy[i] = textCopy[i].replaceAll("<p>", "" + page); textCopy[i] = textCopy[i].replaceAll("<P>", "" + pageCount); } PdfContentByte cb = stamp.getOverContent(page); cb.beginText(); cb.setColorFill(chosenFontColor); cb.setFontAndSize(font, chosenFontSize); Rectangle pageSize = reader.getPageSizeWithRotation(page); cb.showTextAligned(Element.ALIGN_LEFT, textCopy[0], chosenLeftRightMargin, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_CENTER, textCopy[1], pageSize.width() / 2, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[2], pageSize.width() - chosenLeftRightMargin, pageSize.height() - chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_LEFT, textCopy[3], chosenLeftRightMargin, chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_CENTER, textCopy[4], pageSize.width() / 2, chosenTopBottomMargin, 0); cb.showTextAligned(Element.ALIGN_RIGHT, textCopy[5], pageSize.width() - chosenLeftRightMargin, chosenTopBottomMargin, 0); cb.endText(); } } stamp.close(); } catch (Exception e) { ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile); e.printStackTrace(); } finally { tempFile.delete(); } }
From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java
License:Open Source License
/** * This method is for setting the properties of watermark Text. *///from w ww .j a v a2 s. co m private void decoratePdfWatermarkText(PdfContentByte pdfContentByte, Rectangle rectangle, WatermarkBean watermarkBean) { float x, y, x1, y1, angle; final float OPACITY = 0.3f; PdfGState pdfGState = new PdfGState(); pdfGState.setFillOpacity(OPACITY); int pageWidth = (int) rectangle.getWidth(); int pageHeight = (int) rectangle.getHeight(); try { if (watermarkBean.getType().equalsIgnoreCase(WatermarkConstants.WATERMARK_TYPE_TEXT)) { pdfContentByte.beginText(); pdfContentByte.setGState(pdfGState); Color fillColor = watermarkBean.getFont().getColor() == null ? WatermarkConstants.DEFAULT_WATERMARK_COLOR : watermarkBean.getFont().getColor(); pdfContentByte.setColorFill(fillColor); if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_FOOTER)) { pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(), watermarkBean.getPositionFont().getSize()); if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) { pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(), (rectangle.getLeft(rectangle.getBorderWidthLeft()) + rectangle.getRight(rectangle.getBorderWidthRight())) / 2, rectangle.getBottom(rectangle.getBorderWidthBottom() + watermarkBean.getPositionFont().getSize()), 0); } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) { pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(), rectangle.getRight(rectangle.getBorderWidthRight()), rectangle.getBottom(rectangle.getBorderWidthBottom() + watermarkBean.getPositionFont().getSize()), 0); } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) { pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), rectangle.getLeft(rectangle.getBorderWidthLeft()), rectangle.getBottom(rectangle.getBorderWidthBottom() + watermarkBean.getPositionFont().getSize()), 0); } } else if (watermarkBean.getPosition().equals(WatermarkConstants.WATERMARK_POSITION_HEADER)) { pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(), watermarkBean.getPositionFont().getSize()); if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_CENTER)) { pdfContentByte.showTextAligned(Element.ALIGN_CENTER, watermarkBean.getText(), (rectangle.getLeft(rectangle.getBorderWidthLeft()) + rectangle.getRight(rectangle.getBorderWidthRight())) / 2, rectangle.getTop( rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()), 0); } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_RIGHT)) { pdfContentByte.showTextAligned(Element.ALIGN_RIGHT, watermarkBean.getText(), rectangle.getRight(rectangle.getBorderWidthRight()), rectangle.getTop( rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()), 0); } else if (watermarkBean.getAlignment().equals(WatermarkConstants.ALIGN_LEFT)) { pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), rectangle.getLeft(rectangle.getBorderWidthLeft()), rectangle.getTop( rectangle.getBorderWidthTop() + watermarkBean.getPositionFont().getSize()), 0); } } else { pdfContentByte.setFontAndSize(watermarkBean.getFont().getBaseFont(), watermarkBean.getFont().getSize()); int textWidth = (int) pdfContentByte.getEffectiveStringWidth(watermarkBean.getText(), false); int diagonal = (int) Math.sqrt((pageWidth * pageWidth) + (pageHeight * pageHeight)); int pivotPoint = (diagonal - textWidth) / 2; angle = (float) Math.atan((float) pageHeight / pageWidth); x = (float) (pivotPoint * pageWidth) / diagonal; y = (float) (pivotPoint * pageHeight) / diagonal; x1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.sin(angle)); y1 = (float) (((float) watermarkBean.getFont().getSize() / 2) * Math.cos(angle)); pdfContentByte.showTextAligned(Element.ALIGN_LEFT, watermarkBean.getText(), x + x1, y - y1, (float) Math.toDegrees(angle)); } pdfContentByte.endText(); } } catch (Exception exception) { LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + exception.getMessage()); } }