List of usage examples for com.lowagie.text.pdf PdfContentByte ALIGN_CENTER
int ALIGN_CENTER
To view the source code for com.lowagie.text.pdf PdfContentByte ALIGN_CENTER.
Click Source Link
From source file:com.jk.framework.pdf.PDFMergeUtil.java
License:Apache License
/** * Concat PD fs.//from w w w . j a v a 2 s .com * * @param pdfs * the pdfs * @param outputStream * the output stream * @param paginate * the paginate * @throws PdfException * the pdf exception */ // //////////////////////////////////////////////////////////////// public static void concatPDFs(final List<InputStream> pdfs, final OutputStream outputStream, final boolean paginate) throws PdfException { final Document document = new Document(); try { final List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; final Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { final InputStream pdf = iteratorPDFs.next(); final PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } // Create a writer for the outputstream final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); // BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, // BaseFont.CP1252, BaseFont.NOT_EMBEDDED); final PdfContentByte cb = writer.getDirectContent(); // Holds the // PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; final Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { final 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 (final Exception e) { throw new PdfException(e); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (final IOException ioe) { ioe.printStackTrace(); } } }
From source file:com.moss.pdf.template.core.Renderer.java
License:Open Source License
public void render(InputStream in, List<? extends PropertyMapping> fields, OutputStream out) throws Exception { PdfReader reader = new PdfReader(in); Document document = new Document(reader.getPageSizeWithRotation(1)); PdfWriter writer = PdfWriter.getInstance(document, out); document.open();/*from w w w . j ava 2s. co m*/ for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte cb = writer.getDirectContent(); PdfImportedPage customPage = writer.getImportedPage(reader, i); /* * add the page to our new document, turning this page to its * original rotation */ int pageRotation = reader.getPageRotation(i); if (pageRotation > 0) { System.out.println("page rotation found: " + pageRotation); double angle = -((2 * Math.PI) * pageRotation / 360); // double angle = -(Math.PI / 2); cb.addTemplate(customPage, (float) Math.cos(angle), (float) Math.sin(angle), (float) -Math.sin(angle), (float) Math.cos(angle), 0f, // x document.top() + document.topMargin() // y ); } else { cb.addTemplate(customPage, 0f, 0f); } Map<FontName, BaseFont> fonts = new HashMap<FontName, BaseFont>(); for (PropertyMapping field : fields) { if (field.getPageNumber() != i) { continue; } /* * Only builtin fonts are supported at the moment */ BaseFont font; int fontSize; int alignment; String text; float x, y; float rotation; { font = fonts.get(field.getFontName()); if (font == null) { FontName e = field.getFontName(); String name = null; if (FontName.COURIER == e) { name = BaseFont.COURIER; } else if (FontName.COURIER_BOLD == e) { name = BaseFont.COURIER_BOLD; } else if (FontName.COURIER_BOLD_OBLIQUE == e) { name = BaseFont.COURIER_BOLDOBLIQUE; } else if (FontName.COURIER_OBLIQUE == e) { name = BaseFont.COURIER_OBLIQUE; } else if (FontName.HELVETICA == e) { name = BaseFont.HELVETICA; } else if (FontName.HELVETICA_BOLD == e) { name = BaseFont.HELVETICA_BOLD; } else if (FontName.HELVETICA_BOLD_OBLIQUE == e) { name = BaseFont.HELVETICA_BOLDOBLIQUE; } else if (FontName.HELVETICA_OBLIQUE == e) { name = BaseFont.HELVETICA_OBLIQUE; } else if (FontName.TIMES_BOLD == e) { name = BaseFont.TIMES_BOLD; } else if (FontName.TIMES_BOLD_ITALIC == e) { name = BaseFont.TIMES_BOLDITALIC; } else if (FontName.TIMES_ITALIC == e) { name = BaseFont.TIMES_ITALIC; } else if (FontName.TIMES_ROMAN == e) { name = BaseFont.TIMES_ROMAN; } if (name == null) { throw new RuntimeException("Unknown font type: " + e); } font = BaseFont.createFont(name, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); fonts.put(field.getFontName(), font); } fontSize = field.getFontSize(); if (TextAlignment.LEFT == field.getAlignment()) { alignment = PdfContentByte.ALIGN_LEFT; } else if (TextAlignment.CENTER == field.getAlignment()) { alignment = PdfContentByte.ALIGN_CENTER; } else if (TextAlignment.RIGHT == field.getAlignment()) { alignment = PdfContentByte.ALIGN_RIGHT; } else { alignment = PdfContentByte.ALIGN_LEFT; } Object value = p.eval(field.getExpr()); if (value == null) { text = ""; } else { text = value.toString(); } x = field.getX() * POINTS_IN_A_CM; y = field.getY() * POINTS_IN_A_CM; rotation = 0; } cb.beginText(); cb.setFontAndSize(font, fontSize); cb.showTextAligned(alignment, text, x, y, rotation); cb.endText(); } document.newPage(); } reader.close(); document.close(); }
From source file:com.square.adherent.noyau.service.implementations.RelevePrestationServiceImpl.java
License:Open Source License
@Override public FichierDto getRelevePrestationByteArray(Long idRelevePrestation, Long idPersonne, boolean duplicata) { logger.debug(messageSourceUtil.get(MessageKeyUtil.LOGGER_DEBUG_CONVERSION_RELEVE_PRESTATION, new String[] { String.valueOf(idRelevePrestation) })); final CritereSelectionRelevePrestationDto critereSelectionRelevePrestationDto = new CritereSelectionRelevePrestationDto(); critereSelectionRelevePrestationDto.setRelevePrestationId(idRelevePrestation); if (idPersonne != null) { critereSelectionRelevePrestationDto.setIdPersonne(idPersonne); }//from w ww . ja va2 s. co m final List<RelevePrestation> lstReleves = relevePrestationDao .getListeReleveParCriteres(critereSelectionRelevePrestationDto, null); if (lstReleves.size() == 1) { final RelevePrestation releve = lstReleves.get(0); final String error = messageSourceUtil.get(MessageKeyUtil.ERROR_RECUPERATION_FICHIER); FichierDto fichier; final String cheminFichier = serveurEmcRepReleve + File.separator + releve.getNomFichier(); try { fichier = new FichierDto(); fichier.setNomFichier(releve.getNomFichierCommercial()); if (duplicata) { // On appose la mention "DUPLICATA" sur toutes les pages du relev. try { final PdfReader reader = new PdfReader(cheminFichier); final int nombrePages = reader.getNumberOfPages(); final BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE, BaseFont.WINANSI, BaseFont.EMBEDDED); final PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FICHIER_DUPLICATA_TEMP)); final int taillePolice = 56; final int positionX = ((int) PageSize.A4.getWidth()) / 2; final int positionY = ((int) PageSize.A4.getHeight()) / 2; final int rotation = 30; for (int i = 1; i <= nombrePages; i++) { final PdfContentByte over = stamp.getOverContent(i); over.beginText(); over.setColorFill(Color.GRAY); final PdfGState gs1 = new PdfGState(); gs1.setFillOpacity(NIVEAU_TRANSPARENCE); over.setGState(gs1); over.setFontAndSize(bf, taillePolice); over.showTextAligned(PdfContentByte.ALIGN_CENTER, "DUPLICATA", positionX, positionY, rotation); over.endText(); } stamp.close(); reader.close(); fichier.setContenu(IOUtils.toByteArray(new FileInputStream(FICHIER_DUPLICATA_TEMP))); final File file = new File(FICHIER_DUPLICATA_TEMP); file.delete(); } catch (DocumentException e) { throw new TechnicalException( messageSourceUtil.get(MessageKeyUtil.ERROR_IMPOSSIBLE_AJOUTER_MENTION_DUPLICATA, new String[] { releve.getNomFichier() })); } } else { fichier.setContenu(IOUtils.toByteArray(new FileInputStream(cheminFichier))); } fichier.setTypeMime(Magic.getMagicMatch(fichier.getContenu()).getMimeType()); } catch (FileNotFoundException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (IOException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicParseException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicMatchNotFoundException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } catch (MagicException e) { logger.error(error + releve.getNomFichier(), e); throw new TechnicalException(error + cheminFichier); } return fichier; } else { throw new TechnicalException( messageSourceUtil.get(MessageKeyUtil.ERROR_ABSCENCE_RELEVE_PRESTATION_PERSONNE)); } }
From source file:com.t2.compassionMeditation.ViewSessionsActivity.java
License:Open Source License
/** * Create a PDF file based on the contents of the graph *//*from ww w .j a va 2s. c o m*/ void CreatePdf() { // Run the export on a separate thread. new Thread(new Runnable() { @Override public void run() { Document document = new Document(); try { Date calendar = Calendar.getInstance().getTime(); mResultsFileName = "BioZenResults_"; mResultsFileName += (calendar.getYear() + 1900) + "-" + (calendar.getMonth() + 1) + "-" + calendar.getDate() + "_"; mResultsFileName += calendar.getHours() + "-" + calendar.getMinutes() + "-" + calendar.getSeconds() + ".pdf"; PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + mResultsFileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // Note top of PDF = 900 float chartWidth = 332; float chartHeight = 45; float spaceHeight = chartHeight + 30; int horizontalPos = 180; float verticalPos = 780; // Write document header contentByte.beginText(); contentByte.setFontAndSize(baseFont, 20); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "T2 BioZen Report", 300, 800, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, "Generated on: " + calendar.toLocaleString(), 300, 770, 0); contentByte.endText(); contentByte.setLineWidth(1f); verticalPos -= spaceHeight; long startTime = startCal.getTimeInMillis(); long endTime = endCal.getTimeInMillis(); float maxChartValue = 0; float chartYAvg; BioSession tmpSession = sessionItems.get(0); int maxKeys = tmpSession.keyItemNames.length; // Loop through all of the the keys for (int key = 0; key < maxKeys; key++) { //Draw a border rect contentByte.setRGBColorStrokeF(0, 0, 0); contentByte.setLineWidth(1f); contentByte.rectangle(horizontalPos, verticalPos, chartWidth, chartHeight); contentByte.stroke(); // Write band name contentByte.beginText(); contentByte.setFontAndSize(baseFont, 12); BioSession tmpSession1 = sessionItems.get(0); contentByte.showTextAligned(PdfContentByte.ALIGN_RIGHT, tmpSession1.keyItemNames[key], 170, (verticalPos + (chartHeight / 2)) - 5, 0); contentByte.endText(); maxChartValue = 0; // First find the max Y for (BioSession session : sessionItems) { if (session.time >= startTime && session.time <= endTime) { chartYAvg = session.avgFilteredValue[key]; if (chartYAvg > maxChartValue) maxChartValue = chartYAvg; } } float lastY = -1; float xIncrement = 0; if (sessionItems.size() > 0) { xIncrement = chartWidth / sessionItems.size(); } float yIncrement = 0; if (maxChartValue > 0) { yIncrement = chartHeight / maxChartValue; } float highValue = 0; int highTime = 0; float highY = 0; float highX = 0; int lowTime = 0; float lowY = 100; float lowX = chartWidth; float lowValue = maxChartValue; int lCount = 0; String keyName = ""; ArrayList<RegressionItem> ritems = new ArrayList<RegressionItem>(); // Loop through the session points of this key String rawYValues = ""; for (BioSession session : sessionItems) { keyName = session.keyItemNames[key]; if (session.time >= startTime && session.time <= endTime) { chartYAvg = session.avgFilteredValue[key]; rawYValues += chartYAvg + ", "; if (lastY < 0) lastY = (float) chartYAvg; contentByte.setLineWidth(3f); contentByte.setRGBColorStrokeF(255, 0, 0); float graphXFrom = horizontalPos + (lCount * xIncrement); float graphYFrom = verticalPos + (lastY * yIncrement); float graphXTo = (horizontalPos + ((lCount + 1) * xIncrement)); float graphYTo = verticalPos + (chartYAvg * yIncrement); // Log.e(TAG, "[" + graphXFrom + ", " + graphYFrom + "] to [" + graphXTo + ", " + graphYTo + "]"); // Draw the actual graph contentByte.moveTo(graphXFrom, graphYFrom); contentByte.lineTo(graphXTo, graphYTo); contentByte.stroke(); //Add regression Item ritems.add(new RegressionItem(lCount, (chartYAvg * yIncrement))); if (chartYAvg > highValue) { highValue = chartYAvg; highY = graphYTo; highX = graphXTo; highTime = (int) (session.time / 1000); } if (chartYAvg < lowValue) { lowValue = chartYAvg; lowY = graphYTo; lowX = graphXTo; lowTime = (int) (session.time / 1000); } lCount++; lastY = (float) chartYAvg; } // End if (session.time >= startTime && session.time <= endTime ) } // End for (BioSession session : sessionItems) //Draw high low dates if (highY != 0 && lowY != 0) { SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy"); String hDate = dateFormat.format(new Date((long) highTime * 1000L)); String lDate = dateFormat.format(new Date((long) lowTime * 1000L)); contentByte.beginText(); contentByte.setFontAndSize(baseFont, 8); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, hDate, highX, highY, 0); contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, lDate, lowX, lowY, 0); contentByte.endText(); } //Draw Regression Line RegressionResult regression = calculateRegression(ritems); contentByte.saveState(); contentByte.setRGBColorStrokeF(0, 0, 250); contentByte.setLineDash(3, 3, 0); contentByte.moveTo(horizontalPos, verticalPos + (float) regression.intercept); contentByte.lineTo(horizontalPos + chartWidth, (float) ((verticalPos + regression.intercept) + (float) (regression.slope * (chartWidth / xIncrement)))); contentByte.stroke(); contentByte.restoreState(); contentByte.setRGBColorStrokeF(0, 0, 0); // Log.e(TAG, keyName + ": [" + rawYValues + "]"); // Get ready for the next key (and series of database points ) verticalPos -= spaceHeight; if (verticalPos < 30) { document.newPage(); verticalPos = 780 - spaceHeight; } } // End for (int key = 0; key < maxKeys; key++) //document.add(new Paragraph("You can also write stuff directly tot he document like this!")); } catch (DocumentException de) { System.err.println(de.getMessage()); Log.e(TAG, de.toString()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); Log.e(TAG, ioe.toString()); } catch (Exception e) { System.err.println(e.getMessage()); Log.e(TAG, e.toString()); } // step 5: we close the document document.close(); fileExportCompleteHandler.sendEmptyMessage(EXPORT_SUCCESS); } }).start(); }
From source file:com.virtusa.akura.student.controller.MessageBoardController.java
License:Open Source License
/** * Merge many pdf files into one file./*from w w w. j a va 2 s.c o m*/ * * @param streamOfPDFFiles - a list of inputStreams * @param outputStream - an instance of outputStream * @param paginate - a boolean * @throws AkuraAppException - The exception details that occurred when processing */ public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) throws AkuraAppException { final int fontSize = 8, leftRightAlignment = 8; final int min = 0; final int max = 5; final int size = 300; final int xAxis = -150; final int pageHeight = 550; final int pageHieghtfromBottom = 16; final int pageRecHeight = 580; final int recHeightFromBottom = 14; Document document = new Document(PageSize.A4); try { 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 output stream PdfWriter writer = null; BaseFont bf = null; try { writer = PdfWriter.getInstance(document, outputStream); document.open(); bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); } catch (DocumentException e) { e.printStackTrace(); } 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()) { if (currentPageNumber != 2) { document.newPage(); } pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); if (currentPageNumber == 1) { cb.addTemplate(page, 0, xAxis); } else if (currentPageNumber != 2) { cb.addTemplate(page, 0, 0); } // Code for pagination. if (paginate) { cb.beginText(); cb.setFontAndSize(bf, fontSize); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + AkuraWebConstant.REPORT_GPL, size, max, min); cb.newlineText(); cb.endText(); if (currentPageNumber != 2) { int pageNo = currentPageNumber; if (currentPageNumber != 1) { pageNo = currentPageNumber - 1; } // write the page number inside a rectangle. cb.fillStroke(); cb.rectangle(leftRightAlignment, recHeightFromBottom, pageRecHeight, leftRightAlignment); cb.beginText(); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, PAGE + pageNo, pageHeight, pageHieghtfromBottom, 0); cb.endText(); cb.stroke(); } } } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException ioe) { ioe.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 w ww .java 2 s . 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:net.mitnet.tools.pdf.book.pdf.builder.PdfBookBuilder.java
License:Open Source License
public void buildBook(List<File> inputFileList, File outputFile) { try {//from w w w .ja v a 2s . co m 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:org.areasy.common.doclet.document.DocumentEventHandler.java
License:Open Source License
/** * At the end of each page, index information is collected * and footer and headers are inserted.// w w w.j a v a 2 s. c o m * * @param document The current PDF document. * @param writer The writer used to create the document. */ public void onEndPage(PdfWriter writer, Document document) { currentPage = document.getPageNumber(); State.setCurrentPage(currentPage); if (State.getCurrentHeaderType() != HEADER_DEFAULT) { float len; if (State.isContinued() && !State.isLastMethod()) { String cont = "(continued on next page)"; len = bf.getWidthPoint(cont, 7); cb.beginText(); cb.setFontAndSize(bf, 7); cb.setTextMatrix(300 - (len / 2), 56); cb.showText(cont); cb.endText(); } if (State.getCurrentHeaderType() != HEADER_DETAILS) { // add lines cb.setLineWidth(1f); cb.moveTo(LEFT_MARGIN, 812); cb.lineTo(RIGHT_MARGIN, 812); } cb.moveTo(LEFT_MARGIN, 42); cb.lineTo(RIGHT_MARGIN, 42); cb.stroke(); // page footer with number of pages float textX = (float) 0.0; float templateX = (float) 0.0; float textWidth = (float) 0.0; float numWidth = (float) 0.0; int currPageNumberAlign; if (pageNumberAlign == PAGE_NUMBER_ALIGN_SWITCH) { if ((currentPage % 2) == 0) currPageNumberAlign = PAGE_NUMBER_ALIGN_LEFT; else currPageNumberAlign = PAGE_NUMBER_ALIGN_RIGHT; } else currPageNumberAlign = pageNumberAlign; String text = DefaultConfiguration.getString(ARG_PGN_PREFIX, "Page ") + currentPage; if (pageNumberType == PAGE_NUMBER_FULL) text = text + " of "; textWidth = bf.getWidthPoint(text, 8); numWidth = bf.getWidthPoint("999", 8); if (currPageNumberAlign == PAGE_NUMBER_ALIGN_LEFT) textX = LEFT_MARGIN; if (currPageNumberAlign == PAGE_NUMBER_ALIGN_CENTER) textX = (float) (DOCUMENT_WIDTH / 2) - (textWidth / 2); if (currPageNumberAlign == PAGE_NUMBER_ALIGN_RIGHT) textX = RIGHT_MARGIN - textWidth - numWidth; templateX = textX + textWidth; cb.beginText(); cb.setFontAndSize(bf, 8); if (currPageNumberAlign == PAGE_NUMBER_ALIGN_LEFT) { cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text, textX, FOOTER_BASELINE, 0); } if (currPageNumberAlign == PAGE_NUMBER_ALIGN_CENTER) { cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text, textX, FOOTER_BASELINE, 0); } if (currPageNumberAlign == PAGE_NUMBER_ALIGN_RIGHT) { cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text, textX, FOOTER_BASELINE, 0); } cb.endText(); if (pageNumberType == PAGE_NUMBER_FULL) { // add template for total page number cb.addTemplate(template, templateX, FOOTER_BASELINE); } // headers (left, right, center) // temporary solution: handling of first page of package // not correct yet, so use fix heading configuration now if (State.getCurrentHeaderType() == HEADER_API) { leftHeader = ""; centerHeader = "$CLASS"; rightHeader = ""; } if (State.getCurrentHeaderType() == HEADER_INDEX) { leftHeader = ""; centerHeader = "Index"; rightHeader = ""; } if (State.getCurrentHeaderType() == HEADER_DETAILS) { leftHeader = ""; centerHeader = ""; rightHeader = ""; } cb.beginText(); cb.setFontAndSize(bf, 8); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, parseHeader(centerHeader), DOCUMENT_WIDTH / 2, HEADER_BASELINE, 0); cb.endText(); cb.beginText(); cb.setFontAndSize(bf, 8); cb.showTextAligned(PdfContentByte.ALIGN_LEFT, parseHeader(leftHeader), LEFT_MARGIN, HEADER_BASELINE, 0); cb.endText(); cb.beginText(); cb.setFontAndSize(bf, 8); cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, parseHeader(rightHeader), RIGHT_MARGIN, HEADER_BASELINE, 0); cb.endText(); } }
From source file:org.caisi.tickler.web.TicklerPrinter.java
License:Open Source License
public void footer() { PdfContentByte cb = writer.getDirectContent(); cb.saveState();/* ww w . j a v a 2s .c om*/ 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.mapfish.print.PDFUtils.java
License:Open Source License
public static int getHorizontalAlignment(String labelAlign) { /* Valid values for horizontal alignment: "l"=left, "c"=center, "r"=right. */ int myAlignment = PdfContentByte.ALIGN_LEFT; if (labelAlign.toUpperCase().contains("L")) { myAlignment = PdfContentByte.ALIGN_LEFT; }/*from w w w.ja va 2s . c om*/ if (labelAlign.toUpperCase().contains("C")) { myAlignment = PdfContentByte.ALIGN_CENTER; } if (labelAlign.toUpperCase().contains("R")) { myAlignment = PdfContentByte.ALIGN_RIGHT; } return myAlignment; }