List of usage examples for com.itextpdf.text Document setMargins
public boolean setMargins(float marginLeft, float marginRight, float marginTop, float marginBottom)
From source file:com.vectorprint.report.itext.TocOutputStream.java
License:Open Source License
@Override public void secondPass(InputStream firstPass, OutputStream orig) throws IOException { PdfReader reader = null;//from www.j a va2 s. co m VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument(); try { reader = new PdfReader(firstPass); prepareToc(); // init fresh components for second pass styling StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance(); StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings()); _stylerFactory.setLayerManager(outer.getElementProducer()); _stylerFactory.setImageLoader(outer.getElementProducer()); outer.getStyleHelper().setStylerFactory(_stylerFactory); EventHelper event = outer.getEventHelper().getClass().newInstance(); event.setItextStylerFactory(_stylerFactory); event.setElementProvider(outer.getElementProducer()); ((DefaultElementProducer) outer.getElementProducer()).setPh(event); Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper()); PdfWriter w = PdfWriter.getInstance(d, orig); w.setPageEvent(event); outer.getStyleHelper().setVpd((VectorPrintDocument) d); _stylerFactory.setDocument(d, w); DocumentStyler ds = _stylerFactory.getDocumentStyler(); outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds)); d.open(); ds.styleAfterOpen(d, null); List outline = SimpleBookmark.getBookmark(reader); if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) { printToc(d, w, vpd); if (outline != null) { int cur = w.getCurrentPageNumber(); SimpleBookmark.shiftPageNumbers(outline, cur, null); } d.newPage(); } outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString()); for (int p = 1; p <= reader.getNumberOfPages(); p++) { Image page = Image.getInstance(w.getImportedPage(reader, p)); page.setAbsolutePosition(0, 0); d.setPageSize(page); d.newPage(); Chunk i = new Chunk(" "); if (vpd.getToc().containsKey(p)) { Section s = null; for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) { if (e.getKey() == p) { s = e.getValue().get(0); break; } } i.setLocalDestination(s.getTitle().getContent()); } d.add(i); w.getDirectContent().addImage(page); w.freeReader(reader); } if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) { printToc(d, w, vpd); } w.setOutlines(outline); if (outer.isWasDebug()) { event.setLastPage(outer.getWriter().getCurrentPageNumber()); d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210))); d.setMargins(5, 5, 5, 5); d.newPage(); outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString()); event.setDebugHereAfter(true); DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory); } d.close(); } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) { throw new VectorPrintRuntimeException(ex); } finally { if (reader != null) { reader.close(); } } }
From source file:Controller.app.ConsultaController.java
private File createPDF(TblServicioFactura factura) throws IOException { String data = factura.getTesPagoResponse(); JSONObject obj = new JSONObject(data); JSONArray content = obj.getJSONArray("lineaFactura"); String temp = ""; File _file = null;//from ww w . jav a 2 s. c o m Document doc = null; OutputStream file = null; int page = 0; try { _file = File.createTempFile("temp_file", ".pdf"); TblServicioServicio servicio = servicios.search(factura.getTesCodigoSintesisBi().toString()); file = new FileOutputStream(_file); doc = new Document(PageSize.LETTER); doc.setMargins(servicio.getMarginLeft().floatValue(), servicio.getMarginRight().floatValue(), servicio.getMarginTop().floatValue(), servicio.getMarginBottom().floatValue()); PdfWriter.getInstance(doc, file); doc.open(); // ClassLoader classloader = Thread.currentThread().getContextClassLoader(); ClassLoader classloader = getClass().getClassLoader(); URL url = classloader.getResource("cour.ttf"); BaseFont base = null; if (url == null) { base = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } else { String path = url.getPath(); if ("/".equals(path.substring(0, 1))) { path = path.substring(1); } Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, path); base = BaseFont.createFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } Font f = new Font(base, servicio.getFontSize(), Font.NORMAL, BaseColor.BLACK); String qr = ""; float line = 0; for (Object item : content) { Paragraph paragraph = new Paragraph(item.toString(), f); if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) { if (item.toString().contains("P X#X&$#&K##")) { paragraph = new Paragraph(" ", f); doc.add(paragraph); doc.add(paragraph); paragraph = new Paragraph(item.toString(), f); } } if (item.toString().contains("<b>")) { Font bold = new Font(base, 7.0f, Font.BOLD, BaseColor.BLACK); paragraph = new Paragraph(item.toString().replace("<b>", ""), bold); } if (item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>")) { qr = item.toString().replaceAll("<QR>", ""); qr = item.toString().replaceAll("<QR_ENT_G>", ""); Image image = QR.create(qr); image.scaleAbsolute(servicio.getQrScale().floatValue(), servicio.getQrScale().floatValue()); if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL") || servicio.getTesDetalleVc().trim().equals("PAGO TELECEL") || servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL") || servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) { float y = (doc.getPageSize().getHeight() - (paragraph.getLeading() * (line + 1))); float x = 0; if (servicio.getTesDetalleVc().trim().equals("PAGO ENTEL")) { image.setAlignment(Image.ALIGN_RIGHT); x = doc.getPageSize().getWidth() - (110 - servicio.getMarginLeft().floatValue()); } if (servicio.getTesDetalleVc().trim().equals("PAGO TELECEL")) { image.setAlignment(Image.ALIGN_LEFT); x = 30; y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading() * 2)); } if (servicio.getTesDetalleVc().trim().equals("PAGO NUEVATEL")) { image.setAlignment(Image.ALIGN_LEFT); x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue()); y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading())); } if (servicio.getTesDetalleVc().trim().equals("PAGO TIGOSTAR (MULTIVISION)")) { image.setAlignment(Image.ALIGN_LEFT); x = doc.getPageSize().getWidth() - (120 - servicio.getMarginLeft().floatValue()); y -= (servicio.getQrScale().floatValue() - (paragraph.getLeading())); } image.setAbsolutePosition(x, y); } doc.add(image); } if (servicio.getDelimitador().equals(item.toString().trim())) { line = 0; page++; doc.newPage(); } else { line += 1f; if (!(item.toString().contains("<QR>") || item.toString().contains("<QR_ENT_G>"))) { doc.add(paragraph); } } temp += item.toString(); } } catch (FileNotFoundException ex) { Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex); } catch (DocumentException | IOException ex) { Logger.getLogger(ConsultaController.class.getName()).log(Level.INFO, null, ex); } doc.close(); file.close(); return _file; }
From source file:cz.zcu.kiv.eegdatabase.logic.pdf.PDFUtils.java
License:Apache License
public Paragraph setHeader(Document document, String title) throws IOException, BadElementException { Paragraph paragraph = new Paragraph(title, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD, BaseColor.BLACK)); paragraph.setAlignment(Element.ALIGN_CENTER); Image img = GetResizedAndCenteredImage(path + convertPath("/files/images/" + HEADERIMG)); float topMargin = img.getHeight() + 2 * PADDING[0]; img.setAbsolutePosition(PADDING[3], (PageSize.A4.getHeight() - img.getHeight()) - PADDING[0]); paragraph.add(img);//w ww . j a v a 2 s . co m img = GetResizedAndCenteredImage(path + convertPath("/files/images/" + FOOTERIMG)); img.setAbsolutePosition((PageSize.A4.getWidth() - img.getWidth()) / 2, PADDING[2]); paragraph.add(img); float bottomMargin = img.getHeight() + 2 * PADDING[2]; document.setMargins(topMargin, PADDING[1], bottomMargin, PADDING[3]); paragraph.setSpacingAfter(1.5f * PADDING[0]); return paragraph; }
From source file:de.bfs.radon.omsimulation.gui.data.OMExports.java
License:Open Source License
/** * //w w w.j av a 2s . c om * Method to export charts as PDF files using the defined path. * * @param path * The filename and absolute path. * @param chart * The JFreeChart object. * @param width * The width of the PDF file. * @param height * The height of the PDF file. * @param mapper * The font mapper for the PDF file. * @param title * The title of the PDF file. * @throws IOException * If writing a PDF file fails. */ @SuppressWarnings("deprecation") public static void exportPdf(String path, JFreeChart chart, int width, int height, FontMapper mapper, String title) throws IOException { File file = new File(path); FileOutputStream pdfStream = new FileOutputStream(file); BufferedOutputStream pdfOutput = new BufferedOutputStream(pdfStream); Rectangle pagesize = new Rectangle(width, height); Document document = new Document(); document.setPageSize(pagesize); document.setMargins(50, 50, 50, 50); document.addAuthor("OMSimulationTool"); document.addSubject(title); try { PdfWriter pdfWriter = PdfWriter.getInstance(document, pdfOutput); document.open(); PdfContentByte contentByte = pdfWriter.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D g2D = template.createGraphics(width, height, mapper); Double r2D = new Rectangle2D.Double(0, 0, width, height); chart.draw(g2D, r2D); g2D.dispose(); contentByte.addTemplate(template, 0, 0); } catch (DocumentException de) { JOptionPane.showMessageDialog(null, "Failed to write PDF document.\n" + de.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); de.printStackTrace(); } document.close(); }
From source file:de.extra.xtt.util.pdf.PdfCreatorImpl.java
License:Apache License
private Document initPdfWriterAndDocument(String filePath, boolean addHandlerHeaderFooter) throws FileNotFoundException, DocumentException { chapterCounter = 0;/*w w w . j a v a 2 s . com*/ currPageNumber = 1; Document document = new Document(); document.setMargins(40, 40, 55, 55); PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(filePath)); if (addHandlerHeaderFooter) { // Eventhandler fr die Fuzeile HeaderFooter hf = new HeaderFooter(); pdfWriter.setPageEvent(hf); } document.open(); return document; }
From source file:edu.clemson.lph.pdfgen.PDFGen.java
License:Open Source License
private void printDoc() { if (sSourceFile == null || osDest == null) { logger.error("Cannot print nothing"); return;//from ww w . j a v a2s. c o m } boolean bBold = false; boolean bCenter = false; boolean bItalic = false; boolean bSmallItalic = false; boolean bUnderline = false; try { Document doc = new Document(); float fCorr = doc.getPageSize().getWidth() / 8.5f; doc.setMargins(1.0f * fCorr, 1.0f * fCorr, 1.0f * fCorr, 1.0f * fCorr); PdfWriter.getInstance(doc, osDest); doc.open(); BufferedReader br = new BufferedReader(new FileReader(sSourceFile)); String sLine = br.readLine(); while (sLine != null) { bBold = false; bCenter = false; if (sLine.startsWith(".")) { String sRest = sLine.substring(1); String sCodes = sRest.substring(0, sRest.indexOf('.')); sLine = sRest.substring(sRest.indexOf('.') + 1); if ("image".equals(sCodes)) { String sFileName = sLine; com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(sFileName); image.setAlignment(Element.ALIGN_CENTER); doc.add(image); sLine = br.readLine(); continue; } else if ("himage".equals(sCodes)) { String sFileName = sLine; com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(sFileName); image.scaleToFit(500, 40); image.setAlignment(Element.ALIGN_CENTER); doc.add(image); Paragraph p = new Paragraph(" "); doc.add(p); sLine = br.readLine(); continue; } else if ("fimage".equals(sCodes)) { int iBlanks = 9; // How do I figure out how many to get to end? for (int i = 0; i < iBlanks; i++) { Paragraph p = new Paragraph(" "); doc.add(p); } String sFileName = sLine; com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(sFileName); image.scaleToFit(500, 40); image.setAlignment(Element.ALIGN_CENTER); doc.add(image); sLine = br.readLine(); continue; } else if ("list".equals(sCodes)) { String sFullLine = doSub(sLine); StringTokenizer tok = new StringTokenizer(sFullLine, "\n"); List list = new List(List.UNORDERED); while (tok.hasMoreTokens()) { String sNextLine = tok.nextToken(); ListItem listItem = new ListItem(sNextLine, fNormal); list.add(listItem); } doc.add(list); sLine = br.readLine(); continue; } if (sCodes.contains("b")) bBold = true; if (sCodes.contains("c")) bCenter = true; if (sCodes.contains("i")) bItalic = true; if (sCodes.contains("si")) bSmallItalic = true; if (sCodes.contains("u")) bUnderline = true; } if (sLine.trim().length() == 0) sLine = " "; String sFullLine = doSub(sLine); Paragraph p = new Paragraph(); if (bBold) p.setFont(fBold); else if (bSmallItalic) p.setFont(fSmallItalic); else if (bItalic) p.setFont(fItalic); else if (bUnderline) p.setFont(fUnderline); else p.setFont(fNormal); if (bCenter) { p.setAlignment(Element.ALIGN_CENTER); } else { p.setAlignment(Element.ALIGN_LEFT); } p.add(sFullLine); doc.add(p); sLine = br.readLine(); } br.close(); doc.close(); } catch (FileNotFoundException e) { logger.error("Could not find source file " + sSourceFile + " or destination", e); } catch (IOException e) { logger.error("Could not read file " + sSourceFile, e); } catch (DocumentException e) { logger.error("Error creating iText Document", e); } }
From source file:edu.harvard.mcz.precapture.encoder.LabelEncoder.java
License:Open Source License
@SuppressWarnings("hiding") public static boolean printList(ArrayList<ContainerLabel> containers) throws PrintFailedException { log.debug("Invoked printList "); boolean result = false; ContainerLabel label = new ContainerLabel(); if (containers.isEmpty()) { log.debug("No labels to print."); } else {// ww w .j a va 2s . c om LabelDefinitionType printDefinition = null; LabelDefinitionListType printDefs = PreCaptureSingleton.getInstance().getPrintFormatDefinitionList(); List<LabelDefinitionType> printDefList = printDefs.getLabelDefinition(); Iterator<LabelDefinitionType> il = printDefList.iterator(); while (il.hasNext()) { LabelDefinitionType def = il.next(); if (def.getTitle().equals(PreCaptureSingleton.getInstance().getProperties().getProperties() .getProperty(PreCaptureProperties.KEY_SELECTED_PRINT_DEFINITION))) { printDefinition = def; } } if (printDefinition == null) { log.error("No selected print format defintion found."); //TODO change from message to error handling dialog that allows picking a print format. JOptionPane.showMessageDialog(null, "Unable to print. No print format is selected."); } else { log.debug(printDefinition.getTitle()); log.debug(printDefinition.getTextOrentation().toString()); LabelEncoder encoder = new LabelEncoder(containers.get(0)); try { Image image = encoder.getImage(); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(PreCaptureSingleton.getInstance() .getProperties().getProperties().getProperty(PreCaptureProperties.KEY_LABELPRINTFILE))); // Convert units in print definition to points (72 points/inch, 28.346456 points/cm) int paperWidthPoints = 612; // 8.5" int paperHeightPoints = 792; // 11" int marginsPoints = 36; // 0.5" int labelWidthPoints = 540; // 7.5" int labelHeightPoints = 720; // 10" int numColumns = 1; // goes with above numColumns = printDefinition.getColumns(); float relWidthTextCell = printDefinition.getRelWidthTextCell(); float relWidthBarcodeCell = printDefinition.getRelWidthBarcodeCell(); log.debug("relWidthTextCell = " + relWidthTextCell); log.debug("relWidthBarcodeCell = " + relWidthBarcodeCell); if (printDefinition.getUnits().toString().toLowerCase().equals("inches")) { paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 72f); paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 72f); marginsPoints = (int) Math.floor(printDefinition.getMargins() * 72f); labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 72f); labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 72f); } if (printDefinition.getUnits().toString().toLowerCase().equals("cm")) { paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 28.346456f); paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 28.346456f); marginsPoints = (int) Math.floor(printDefinition.getMargins() * 28.346456f); labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 28.346456f); labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 28.346456f); } if (printDefinition.getUnits().toString().toLowerCase().equals("points")) { paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 1f); paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 1f); marginsPoints = (int) Math.floor(printDefinition.getMargins() * 1f); labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 1f); labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 1f); } if (paperWidthPoints == 612 && paperHeightPoints == 792) { document.setPageSize(PageSize.LETTER); } else { document.setPageSize(new Rectangle(paperWidthPoints, paperHeightPoints)); } document.setMargins(marginsPoints, marginsPoints, marginsPoints, marginsPoints); document.open(); // Sanity check if (paperWidthPoints <= 0) { paperWidthPoints = 612; } if (paperHeightPoints <= 0) { paperHeightPoints = 792; } if (marginsPoints < 0) { marginsPoints = 0; } if (labelWidthPoints <= 0) { labelWidthPoints = 540; } if (labelHeightPoints <= 0) { labelHeightPoints = 720; } if (paperWidthPoints + (marginsPoints * 2) < labelWidthPoints) { labelWidthPoints = paperWidthPoints + (marginsPoints * 2); log.debug("Adjusting label width to fit printable page width"); } if (paperHeightPoints + (marginsPoints * 2) < labelHeightPoints) { labelHeightPoints = paperHeightPoints + (marginsPoints * 2); log.debug("Adjusting label height to fit printable page height"); } // calculate how many columns will fit on the paper. int columns = (int) Math.floor((paperWidthPoints - (marginsPoints * 2)) / labelWidthPoints); // if specified column count is smaller, use the specified. if (numColumns < columns) { columns = numColumns; log.debug( "Fewer columns specified in definition than will fit on page, using specified column count of " + numColumns); } // define two table cells per column, one for text one for barcode. int subCellColumnCount = columns * 2; // set the table, with an absolute width and relative widths of the cells in the table; PdfPTable table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns, subCellColumnCount, relWidthTextCell, relWidthBarcodeCell); // figure out the width of the cells containing the barcodes. float ratio = ((float) relWidthBarcodeCell) / (((float) relWidthBarcodeCell) + ((float) relWidthTextCell)); float barcodeCellWidthPoints = (float) Math.floor(labelWidthPoints * ratio); log.debug("Width of barcode cell in points: " + barcodeCellWidthPoints); //Rectangle pageSizeRectangle = new Rectangle(paperWidthPoints, paperHeightPoints); //table.setWidthPercentage(cellWidthsPoints, pageSizeRectangle); //table.setTotalWidth(cellWidthsPoints); // Calculate how many cells fit on a page (two cells per label). int labelsPerColumn = (int) Math .floor((paperHeightPoints - (marginsPoints * 2)) / labelHeightPoints); int cellsPerPage = subCellColumnCount * labelsPerColumn; log.debug("Labels per column = " + labelsPerColumn); log.debug("Cells per page = " + cellsPerPage); Iterator<ContainerLabel> iterLabels = containers.iterator(); int cellCounter = 0; // counts number of cells filled on a page. int counter = 0; // counts number of pre capture label data rows to print (each of which may request more than one copy). // TODO: Doesn't fit on page. while (iterLabels.hasNext()) { // Loop through all of the container labels found to print label = iterLabels.next(); if (label != null) { log.debug(label); log.debug("Label: " + counter + " " + label.toString()); for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) { // For each container label, loop through the number of requested copies // Generate a text and a barcode cell for each, and add to array for page int toPrintPlus = toPrint + 1; // for pretty counter in log. log.debug("Copy " + toPrintPlus + " of " + label.getNumberToPrint()); PdfPCell cell = label.toPDFCell(printDefinition); cell.setFixedHeight(labelHeightPoints); // Colors to illustrate where the cells are on the layout if (PreCaptureSingleton.getInstance().getProperties().getProperties() .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) { cell.setBackgroundColor(new BaseColor(255, 255, 30)); } PdfPCell cell_barcode = new PdfPCell(); cell_barcode.setBorderColor(BaseColor.LIGHT_GRAY); cell_barcode.disableBorderSide(PdfPCell.LEFT); cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP); cell_barcode.setHorizontalAlignment(Element.ALIGN_RIGHT); cell_barcode.setFixedHeight(labelHeightPoints); if (PreCaptureSingleton.getInstance().getProperties().getProperties() .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) { cell_barcode.setBackgroundColor(new BaseColor(255, 30, 255)); } encoder = new LabelEncoder(label); image = encoder.getImage(); image.setAlignment(Image.ALIGN_TOP); //image.setAlignment(Image.ALIGN_LEFT); image.setAlignment(Image.ALIGN_RIGHT); image.scaleToFit(barcodeCellWidthPoints, labelHeightPoints); cell_barcode.addElement(image); table.addCell(cell); table.addCell(cell_barcode); cellCounter = cellCounter + 2; // we've added two cells to the page (two cells per label). log.debug("Cells " + cellCounter + " of " + cellsPerPage + " cells per page."); // If we have hit a full set of labels for the page, add them to the document // in each column, filling left to right if (cellCounter >= cellsPerPage - 1) { log.debug("Page is full"); log.debug("Table has " + table.getNumberOfColumns() + " columns and " + table.getRows().size() + " rows "); // Reset to begin next page cellCounter = 0; table.setLockedWidth(true); document.add(table); log.debug("Adding new page"); document.newPage(); table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns, subCellColumnCount, relWidthTextCell, relWidthBarcodeCell); log.debug("Setup new table"); } } // end loop through toPrint (for a taxon/precapture label data row) counter++; // Increment number of pre capture label data rows. } // end if not null label } // end while results has next (for all taxa requested) // get any remaining cells in pairs if (cellCounter > 0) { log.debug("Adding remaining cells in partial page"); if (cellCounter <= cellsPerPage) { for (int i = cellCounter; i <= cellsPerPage; i++) { PdfPCell emptyCell = new PdfPCell(); emptyCell.setBorder(PdfPCell.NO_BORDER); table.addCell(emptyCell); } } log.debug("Table has " + table.getNumberOfColumns() + " columns and " + table.getRows().size() + " rows "); table.setLockedWidth(true); document.add(table); } document.close(); // send to printer PrintingUtility.sendPDFToPrinter(printDefinition, paperWidthPoints, paperHeightPoints); // Check to see if there was content in the document. if (counter == 0) { result = false; } else { // Printed to pdf ok. result = true; } } catch (FileNotFoundException e) { log.debug(e.getMessage(), e); throw new PrintFailedException("File not found."); } catch (DocumentException e) { log.error(e.getMessage(), e); throw new PrintFailedException("Error building/printing PDF document. " + e.getMessage()); } catch (OutOfMemoryError e) { System.out.println("Out of memory error. " + e.getMessage()); System.out.println("Failed. Too many labels."); throw new PrintFailedException("Ran out of memory, too many labels at once."); } catch (BarcodeCreationException e) { System.out.println("BarcodeCreationException. " + e.getMessage()); System.out.println("Failed. Couldn't create barcode."); throw new PrintFailedException( "Unable to create barcode. Probably too many characters to encode. " + e.getMessage()); } } log.debug("printList Done. Success = " + result); } return result; }
From source file:es.sm2.openppm.front.utils.DocumentUtils.java
License:Open Source License
/** * Create PDF for Control Change//from w w w . j a va 2s . c om * @param idioma * @param project * @param change * @param preparedBy * @return * @throws DocumentException * @throws LogicException */ public static byte[] toPdf(ResourceBundle idioma, Project project, Changecontrol change, Employee preparedBy, final Image headerImg, final Image footerImg) throws DocumentException, LogicException { if (change == null) { throw new DocumentException("No change control found."); } if (preparedBy == null || preparedBy.getContact() == null) { throw new UserSendingException(); } Document document = new Document(PageSize.A4); document.setMargins(70F, 70F, 38F, 38F); // Total Height: 842pt, Total Width: 595pt byte[] file = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); @SuppressWarnings("unused") PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream); document.open(); Font fontHeader = new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD); Font fontCell = new Font(FontFamily.TIMES_ROMAN, 9); Font tituloFont = new Font(FontFamily.TIMES_ROMAN, 16, Font.BOLD); document.add(new Paragraph(" ", tituloFont)); document.add(new Paragraph(" ", tituloFont)); document.add(new Paragraph(" ", fontHeader)); Paragraph title = new Paragraph(idioma.getString("change_request").toUpperCase(), tituloFont); title.setAlignment(Paragraph.ALIGN_CENTER); document.add(title); // Header Table // Project info PdfPTable tableHeader = new PdfPTable(3); tableHeader.setWidthPercentage(100); tableHeader.setSpacingBefore(10); tableHeader.setSpacingAfter(15); int[] colWidth = new int[3]; colWidth[0] = 40; colWidth[1] = 30; colWidth[2] = 30; tableHeader.setWidths(colWidth); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.project_name"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.prepared_by"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell(prepareHeaderCell(idioma.getString("change_request.date"), fontHeader, 1F, 1F, 0F, 1F)); tableHeader.addCell(prepareCell(project.getProjectName() + " / " + project.getAccountingCode(), fontCell, 0F, 0F, 0F, 1F)); tableHeader.addCell(prepareCell(preparedBy.getContact().getFullName(), fontCell, 0F, 0F, 0F, 1F)); tableHeader.addCell(prepareCell(DateUtil.format(idioma, new Date()), fontCell, 0F, 1F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.customer"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.contact_name"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.customer_type"), fontHeader, 1F, 1F, 0F, 1F)); tableHeader.addCell(prepareCell(project.getCustomer() != null ? project.getCustomer().getName() : "", fontCell, 0F, 0F, 0F, 1F)); tableHeader.addCell(prepareCell((project.getCustomer() != null ? project.getCustomer().getName() : "-"), fontCell, 0F, 0F, 0F, 1F)); Customertype cusType = (project.getCustomer() != null ? project.getCustomer().getCustomertype() : null); tableHeader.addCell(prepareCell(cusType == null ? "" : cusType.getName(), fontCell, 0F, 1F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.business_manager"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.project_manager"), fontHeader, 1F, 0F, 0F, 1F)); tableHeader.addCell( prepareHeaderCell(idioma.getString("change_request.originator"), fontHeader, 1F, 1F, 0F, 1F)); Employee bm = project.getEmployeeByFunctionalManager(); Employee pm = project.getEmployeeByProjectManager(); tableHeader.addCell(prepareCell(bm == null ? "" : bm.getContact().getFullName(), fontCell, 0F, 0F, 1F, 1F)); tableHeader.addCell(prepareCell(pm == null ? "" : pm.getContact().getFullName(), fontCell, 0F, 0F, 1F, 1F)); tableHeader.addCell(prepareCell(change.getOriginator(), fontCell, 0F, 1F, 1F, 1F)); document.add(tableHeader); // Change Information document.add(new Paragraph(idioma.getString("change_information"))); PdfPTable tableInfo = new PdfPTable(1); tableInfo.setWidthPercentage(100); tableInfo.setSpacingBefore(10); tableInfo.setSpacingAfter(15); tableInfo.addCell(prepareHeaderCell(idioma.getString("change.change_type"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(change.getChangetype().getDescription(), fontCell, 0F, 1F, 0F, 1F)); String priorityDesc = ""; if (change.getPriority().equals('H')) priorityDesc = idioma.getString("change.priority.high"); if (change.getPriority().equals('N')) priorityDesc = idioma.getString("change.priority.normal"); if (change.getPriority().equals('L')) priorityDesc = idioma.getString("change.priority.low"); tableInfo.addCell(prepareHeaderCell(idioma.getString("change.priority"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(priorityDesc, fontCell, 0F, 1F, 0F, 1F)); tableInfo.addCell(prepareHeaderCell(idioma.getString("change.desc"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(change.getDescription(), fontCell, 0F, 1F, 0F, 1F)); tableInfo.addCell( prepareHeaderCell(idioma.getString("change.recommended_solution"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(change.getRecommendedSolution(), fontCell, 0F, 1F, 1F, 1F)); PdfPTable tableSubInfo = new PdfPTable(3); tableSubInfo.setWidthPercentage(100); //TODO MIGRACION tableSubInfo.addCell(prepareSubCell(idioma.getString("change.wbs_node"), fontHeader)); tableSubInfo.addCell(prepareSubCell(idioma.getString("change.estimated_effort"), fontHeader)); tableSubInfo.addCell(prepareSubCell(idioma.getString("change.estimated_cost"), fontHeader)); tableSubInfo.addCell( prepareSubCell((change.getWbsnode() != null ? change.getWbsnode().getName() : ""), fontCell)); tableSubInfo.addCell(prepareSubCell( (change.getEstimatedEffort() != null ? String.valueOf(change.getEstimatedEffort()) : ""), fontCell)); tableSubInfo.addCell(prepareSubCell( (change.getEstimatedCost() != null ? ValidateUtil.toCurrency(change.getEstimatedCost()) : ""), fontCell)); PdfPCell subTable = new PdfPCell(tableSubInfo); subTable.setBorderWidth(1F); tableInfo.addCell(subTable); tableInfo.addCell(prepareHeaderCell(idioma.getString("change.impact_desc"), fontHeader, 1F, 1F, 0F, 1F)); tableInfo.addCell(prepareCell(change.getImpactDescription(), fontCell, 0F, 1F, 1F, 1F)); document.add(tableInfo); document.add(new Paragraph(idioma.getString("change.resolution"))); PdfPTable tableResolution = new PdfPTable(1); tableResolution.setWidthPercentage(100); tableResolution.setSpacingBefore(10); tableResolution.setSpacingAfter(15); tableResolution .addCell(prepareHeaderCell(idioma.getString("change.resolution"), fontHeader, 1F, 1F, 0F, 1F)); tableResolution.addCell( prepareCell((change.getResolution() != null && change.getResolution() ? idioma.getString("yes") : idioma.getString("no")), fontCell, 0F, 1F, 0F, 1F)); tableResolution .addCell(prepareHeaderCell(idioma.getString("change.resolution_date"), fontHeader, 1F, 1F, 0F, 1F)); tableResolution.addCell( prepareCell(DateUtil.format(idioma, change.getResolutionDate()), fontCell, 0F, 1F, 0F, 1F)); tableResolution.addCell( prepareHeaderCell(idioma.getString("change.resolution_reason"), fontHeader, 1F, 1F, 0F, 1F)); tableResolution.addCell(prepareCell(change.getResolutionReason(), fontCell, 0F, 1F, 1F, 1F)); document.add(tableResolution); document.close(); try { PdfReader reader = new PdfReader(outputStream.toByteArray()); PdfStamper stamper = new PdfStamper(reader, outputStream); int numPag = reader.getNumberOfPages(); for (int i = 1; i <= reader.getNumberOfPages(); i++) { setHeaderFooter(i, numPag, headerImg, footerImg, reader, stamper, idioma); } stamper.close(); } catch (IOException e) { e.printStackTrace(); } file = outputStream.toByteArray(); return file; }
From source file:eu.geopaparazzi.plugins.pdfexport.PdfExportDialogFragment.java
License:Open Source License
private void startExport() { final Context context = getContext(); new AsyncTask<String, Void, String>() { protected String doInBackground(String... params) { File pdfOutputFile = null; try { boolean hasAtLeastOne = false; /*/*from w w w . j av a 2 s . c o m*/ * get notes */ List<Note> notesList = DaoNotes.getNotesList(null, false); if (notesList.size() == 0) { return NODATA; } if (isInterrupted) return INTERRUPTED; File pdfExportDir = ResourcesManager.getInstance(getActivity()).getMainStorageDir(); String filename = ResourcesManager.getInstance(getActivity()).getApplicationName() + "_projectexport_" + TimeUtilities.INSTANCE.TIMESTAMPFORMATTER_LOCAL.format(new Date()) + ".pdf"; pdfOutputFile = new File(pdfExportDir, filename); if (exportPath != null) { pdfOutputFile = new File(exportPath); } // TODO export list to pdf Document document = new Document(); document.setMargins(36, 36, 36, 36); PdfWriter.getInstance(document, new FileOutputStream(pdfOutputFile)); document.open(); document.addTitle("Geopaparazzi PDF Export"); document.addSubject("Geopaparazzi PDF Export"); document.addKeywords("geopaparazzi, export, notes"); document.addAuthor("Geopaparazzi User"); document.addCreator("Geopaparazzi - http://www.geopaparazzi.eu"); int index = 1; for (Note note : notesList) { processNote(document, note, index++); } document.close(); return pdfOutputFile.getAbsolutePath(); } catch (Exception e) { // cleanup as it might be inconsistent if (pdfOutputFile != null && pdfOutputFile.exists()) { pdfOutputFile.delete(); } GPLog.error(this, e.getLocalizedMessage(), e); e.printStackTrace(); return ""; //$NON-NLS-1$ } } protected void onPostExecute(String response) { // on UI thread! progressBar.setVisibility(View.GONE); if (response.equals(NODATA)) { String msg = context.getString(R.string.no_data_found_in_project_to_export); alertDialog.setMessage(msg); } else if (response.equals(INTERRUPTED)) { alertDialog.setMessage(context.getString(R.string.interrupted_by_user)); } else if (response.length() > 0) { String msg = context.getString(R.string.datasaved) + " " + response; alertDialog.setMessage(msg); } else { String msg = context.getString(R.string.data_nonsaved); alertDialog.setMessage(msg); } if (positiveButton != null) positiveButton.setEnabled(true); } }.execute((String) null); }
From source file:Export.CertificadoCargaMaritima.java
public String criarDoc(String numApolice, String numCliente, Contrato c, CargaMaritimaBean cm, String user, String moeda, String arquivo) { try {//from w w w. ja v a 2 s .com SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh'.'mm'.'ss"); Font fontCabecalhoN = FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED, 9.5f); Font fontCorpo = FontFactory.getFont(Fontes.FONT, BaseFont.WINANSI, BaseFont.EMBEDDED, 9f); Font fontCorpoP = FontFactory.getFont(Fontes.FONT, BaseFont.WINANSI, BaseFont.EMBEDDED, 8f); Font fontCorpoN = FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED, 9f); Font fontCorpoNG = FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED, 10f); Font fontCabecalhoNG = FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED, 16f, Font.UNDERLINE); Font fontUK = FontFactory.getFont(Fontes.FONTB, BaseFont.WINANSI, BaseFont.EMBEDDED, 5.5f, Font.ITALIC); PdfPTable pTableEmpresaPricipal = new PdfPTable(new float[] { 25f, 75f }); PdfPTable pTableEmpresaInforImpres1 = new PdfPTable(1); PdfPTable pTableEmpresaInforImpres2 = new PdfPTable(1); PdfPTable pTableEmpresaInforImpres5 = new PdfPTable(1); PdfPTable pTableNull = new PdfPTable(1); PdfPCell cellNull = new PdfPCell(new Phrase(" ", fontCorpo)); cellNull.setBorder(0); pTableNull.addCell(cellNull); PdfPCell pCellNomeEmpresa = new PdfPCell(new Phrase(Empresa.NOME, fontCabecalhoNG)); pCellNomeEmpresa.setBorder(0); PdfPCell pCellNomeEndereco = new PdfPCell(new Phrase(Empresa.ENDERECO, fontCabecalhoN)); pCellNomeEndereco.setBorder(0); PdfPCell pCellCaixaPostal = new PdfPCell(new Phrase(Empresa.CAIXAPOSTAL, fontCabecalhoN)); pCellCaixaPostal.setBorder(0); PdfPCell pCellTeleFax = new PdfPCell( new Phrase(Empresa.TELEFAX + " " + ConfigDoc.Empresa.EMAIL, fontCabecalhoN)); pCellTeleFax.setBorder(0); PdfPCell pCellSociedade = new PdfPCell(new Phrase(Empresa.SOCIEDADE, fontCabecalhoN)); pCellSociedade.setBorder(0); PdfPCell pCellPolice = new PdfPCell(new Phrase(Empresa.APOLICE + numApolice, fontCabecalhoN)); pCellPolice.setBorder(0); Image imageEmpresa = Image.getInstance("logo.png"); imageEmpresa.scaleToFit(120f, 85f); pTableEmpresaInforImpres1.addCell(pCellNomeEmpresa); pTableEmpresaInforImpres1.addCell(pCellNomeEndereco); pTableEmpresaInforImpres1.addCell(pCellCaixaPostal); pTableEmpresaInforImpres1.addCell(pCellTeleFax); pTableEmpresaInforImpres1.addCell(pCellSociedade); pTableEmpresaInforImpres1.addCell(pCellPolice); PdfPCell cellTabela3 = new PdfPCell(pTableEmpresaInforImpres1); cellTabela3.setBorder(0); pTableEmpresaInforImpres5.addCell(cellTabela3); PdfPCell cellTabela5 = new PdfPCell(pTableEmpresaInforImpres5); cellTabela5.setBorder(0); PdfPCell cellTabela6 = new PdfPCell(imageEmpresa); cellTabela6.setBorder(0); pTableEmpresaPricipal.addCell(cellTabela6); pTableEmpresaPricipal.addCell(cellTabela5); PdfPTable pTableTitulo = new PdfPTable(1); Phrase pTitulo = new Phrase("CErtificado Seguro de Carga Maritima".toUpperCase(), fontCorpoNG); pTitulo.add(new Phrase("\nMARINE CARGO CERTIFICATE", fontUK)); PdfPCell cellTitulo = new PdfPCell(pTitulo); cellTitulo.setBorder(0); cellTitulo.setHorizontalAlignment(Element.ALIGN_CENTER); pTableTitulo.addCell(cellTitulo); PdfPTable pTableCorpoUm = new PdfPTable(new float[] { 100 }); PdfPTable pTableCorpoDois = new PdfPTable(new float[] { 50, 50 }); PdfPTable pTableCorpoTres = new PdfPTable(new float[] { 100 }); PdfPCell cellCorpopUm = new PdfPCell(); cellCorpopUm.setBorder(0); PdfPCell cellCorpopDois1 = new PdfPCell(); cellCorpopDois1.setBorder(0); PdfPCell cellCorpopDois2 = new PdfPCell(); cellCorpopDois2.setBorder(0); PdfPCell cellCorpopTres = new PdfPCell(); cellCorpopTres.setBorder(0); Paragraph pCorpoUm1 = new Paragraph( "Certificado de seguro emitido sob contracto aberto n".toUpperCase(), fontCorpoN); pCorpoUm1.add( new Phrase("\ncertificate OF insurance issued under contract open No.".toUpperCase(), fontUK)); Paragraph pCorpoUm2 = new Paragraph("mbito da cobertura: ".toUpperCase(), fontCorpoN); pCorpoUm2.add(new Phrase("\nSCOPE OF COVER", fontUK)); Paragraph pCorpoUm3 = new Paragraph( "Este certificado atesta que a Companhia tem as mencionadas, sob seguro para viagem (s) e valore (s) declarados em favor de", fontCorpo); pCorpoUm3.add(new Phrase( "\nTHIS IS TO CERTIFY THAT THE COMPANY HAS INSURED THE UNDER MENTIONED GOODS FOR THE VOYGE (S) AND VALUE (S) STATED ON BEHALF OF", fontUK)); cellCorpopUm.addElement(pCorpoUm1); cellCorpopUm.addElement(pCorpoUm2); cellCorpopUm.addElement(pCorpoUm3); pTableCorpoUm.addCell(cellCorpopUm); Paragraph pCorpoDois11 = new Paragraph("Taxa Maritima: ", fontCorpo); pCorpoDois11.add(new Phrase("\nMARINE RATE", fontUK)); Paragraph pCorpoDois12 = new Paragraph("Taxa Guerra: ", fontCorpo); pCorpoDois12.add(new Phrase("\nWAR RATE", fontUK)); cellCorpopDois1.addElement(pCorpoDois11); cellCorpopDois1.addElement(pCorpoDois12); pTableCorpoDois.addCell(cellCorpopDois1); cellCorpopUm.addElement(pCorpoUm1); cellCorpopUm.addElement(pCorpoUm2); Paragraph pCorpoDois21 = new Paragraph("Nota de Bebito: ", fontCorpo); pCorpoDois21.add(new Phrase("\nDEBIT NOTE NO", fontUK)); Paragraph pCorpoDois22 = new Paragraph("Total de Prmio: ", fontCorpo); pCorpoDois22.add(new Phrase("\nGROSS PREMIUM", fontUK)); cellCorpopDois2.addElement(pCorpoDois21); cellCorpopDois2.addElement(pCorpoDois22); pTableCorpoDois.addCell(cellCorpopDois2); Paragraph pCorpoTres1 = new Paragraph("Taxa Superintendente: ", fontCorpo); pCorpoTres1.add(new Phrase("\nSuperintendent RATE".toUpperCase(), fontUK)); Paragraph pCorpoTres2 = new Paragraph("Taxa Interna de Trnsito: ", fontCorpo); pCorpoTres2.add(new Phrase("\nINLANDTraffic Rate", fontUK)); Paragraph pCorpoTres3 = new Paragraph("Taxa Total: ", fontCorpo); pCorpoTres3.add(new Phrase("\nTOTAL RATE", fontUK)); Paragraph pCorpoTres4 = new Paragraph("Segurado: ", fontCorpo); pCorpoTres4.add(new Phrase("\nInsured".toUpperCase(), fontUK)); Paragraph pCorpoTres5 = new Paragraph("Meio de Transporte: " + cm.getCargaMaritima().getFormaEnvio(), fontCorpo); pCorpoTres5.add(new Phrase("\nMODE OF CONVEYANCE", fontUK)); //Paragraph pCorpoTres6_1 = new Paragraph("Medadoria Assegurada: ",fontCorpo); Paragraph pCorpoTres6 = new Paragraph("De " + cm.getCargaMaritima().getPaisOrigem() + " Para: " + cm.getCargaMaritima().getPaisDestino(), fontCorpo); pCorpoTres6.add(new Phrase("\nFROM TO", fontUK)); Paragraph pCorpoTres7 = new Paragraph("Juros: ", fontCorpo); pCorpoTres7.add(new Phrase("\nINTEREST", fontUK)); Paragraph pCorpoTres8 = new Paragraph("Valor Segurado: ", fontCorpo); pCorpoTres8.add(new Phrase("\nINSURED VALUE", fontUK)); Paragraph pCorpoTres9 = new Paragraph( "CONDIES: Sujeitas as seguintes clsulas e garantias (Ver anexo A)", fontCorpoN); pCorpoTres9.add(new Phrase( "\nCONDITIONS : Subject to the following clsulas and warranteis (SEE APPENDICIX A)", fontUK)); Paragraph pCorpoTres10 = new Paragraph( "No caso de perda ou dano que se presume a companhia ser reponsvel, deve-se comunicar de imediato NICOM SEGUROS STP" + " para ser feita a vistoria (Por favor volte).", fontCorpo); pCorpoTres10.add(new Phrase( "\nIn the event of loss or damage for which company is presumed to be liable, immediate resquest for survey must be made to NICON SEGUROS STP (PLEASE TURN OVER).", fontUK)); Paragraph pCorpoTres11 = new Paragraph( "No caso de perda ou dano este certificado, depois de autenticado, deve ser anexo a reclamao acompanhado" + " de relatrio de auditoria e da factura original do desembarque, a cpia autenticada ou original da factura e uaisquer outros documentos relativo.", fontCorpo); pCorpoTres10.add(new Phrase( "\nIn case of loss or damage this certificate, must be annexed to the claim note accompaneid by the repost, original bill of landing, true copy" + " or original invoice and any other relevant documenent.", fontUK)); Paragraph pCorpoTres12 = new Paragraph(); Phrase p1 = new Phrase("Nota: ", fontCorpoN); Phrase p2 = new Phrase( "A Empresa compromete-se a emitir uma aplice que cobre as mercadorias descritas no pedido", fontCorpo); Phrase p3 = new Phrase( "\nThe Company undertakes to issue a policy covering the good described herein on request.", fontUK); pCorpoTres12.add(p1); pCorpoTres12.add(p2); pCorpoTres12.add(p3); cellCorpopTres.addElement(pCorpoTres1); cellCorpopTres.addElement(pCorpoTres2); cellCorpopTres.addElement(pCorpoTres3); cellCorpopTres.addElement(pCorpoTres4); cellCorpopTres.addElement(pCorpoTres5); //cellCorpopTres.addElement(pCorpoTres6_1); cellCorpopTres.addElement(pCorpoTres6); cellCorpopTres.addElement(pCorpoTres7); cellCorpopTres.addElement(pCorpoTres8); cellCorpopTres.addElement(cellNull.getPhrase()); cellCorpopTres.addElement(pCorpoTres9); cellCorpopTres.addElement(pCorpoTres10); cellCorpopTres.addElement(cellNull.getPhrase()); cellCorpopTres.addElement(pCorpoTres11); cellCorpopTres.addElement(cellNull.getPhrase()); cellCorpopTres.addElement(pCorpoTres12); pTableCorpoTres.addCell(cellCorpopTres); PdfPTable pTableAssinaturaTitulo = new PdfPTable(1); PdfPTable pTableAssinatura = new PdfPTable(new float[] { 50f, 50f }); Paragraph pUK = new Paragraph("", fontCorpo); pUK.add(new Phrase("Assinaturas", fontCorpoN)); pUK.add(new Phrase("Signature", fontUK)); PdfPCell cellAssinatora = new PdfPCell(pUK); cellAssinatora.setBorder(0); cellAssinatora.setHorizontalAlignment(Element.ALIGN_CENTER); PdfPCell celllinha1 = new PdfPCell( new Phrase("___________________________________".toUpperCase(), fontCorpo)); celllinha1.setBorder(0); celllinha1.setHorizontalAlignment(Element.ALIGN_CENTER); PdfPCell celllinha2 = new PdfPCell( new Phrase("___________________________________".toUpperCase(), fontCorpo)); celllinha2.setBorder(0); celllinha2.setHorizontalAlignment(Element.ALIGN_CENTER); pUK = new Paragraph("", fontCorpo); pUK.add(new Phrase("Pela NICON SEGUROS STP", fontCorpoN)); pUK.add(new Phrase("For NICON SEGUROS STP", fontUK)); PdfPCell celllinha11 = new PdfPCell(pUK); celllinha11.setBorder(0); celllinha11.setHorizontalAlignment(Element.ALIGN_CENTER); pUK = new Paragraph("", fontCorpo); pUK.add(new Phrase("O Segurado", fontCorpoN)); pUK.add(new Phrase("Insured", fontUK)); PdfPCell celllinha21 = new PdfPCell(pUK); celllinha21.setBorder(0); celllinha21.setHorizontalAlignment(Element.ALIGN_CENTER); pTableAssinaturaTitulo.addCell(cellAssinatora); pTableAssinatura.addCell(celllinha1); pTableAssinatura.addCell(celllinha2); pTableAssinatura.addCell(celllinha11); pTableAssinatura.addCell(celllinha21); Document documento = new Document(); documento.setPageSize(PageSize.A4); documento.setMargins(20f, 20f, 35f, 5f); File f = new File(arquivo + "/" + user + "/Seguro Carga Maritima/"); f.mkdirs(); String Ddata = sdf.format(new Date()); f = new File(f.getAbsoluteFile() + "/" + "Certificado Carga Maritima " + Ddata + ".pdf"); reString = "../Documentos/" + user + "/Seguro Carga Maritima/" + "Certificado Carga Maritima " + Ddata + ".pdf"; OutputStream outputStraem = new FileOutputStream(f); PdfWriter writer = PdfWriter.getInstance(documento, outputStraem); if (MarcaDAgua.isSimulation) { MarcaDAgua.SimulacaoVertical v = new MarcaDAgua.SimulacaoVertical(); writer.setPageEvent(v); } if (MarcaDAgua.isCanceled) { MarcaDAgua.AnulacaoVertical v = new MarcaDAgua.AnulacaoVertical(); writer.setPageEvent(v); } documento.open(); documento.add(pTableEmpresaPricipal); documento.add(pTableNull); documento.add(pTableTitulo); documento.add(pTableNull); documento.add(pTableNull); documento.add(pTableCorpoUm); documento.add(pTableNull); documento.add(pTableCorpoDois); documento.add(pTableCorpoTres); documento.add(pTableNull); documento.add(pTableNull); documento.add(pTableAssinaturaTitulo); documento.add(pTableNull); documento.add(pTableNull); documento.add(pTableNull); documento.add(pTableAssinatura); documento.close(); // PrintPdf printPdf = new PrintPdf(f.getAbsolutePath(), f.getAbsolutePath(), 0, 595f,842f,"Enviar Para o OneNote 2013",1); // //PrintPdf printPdf = new PrintPdf(f.getAbsolutePath(), f.getAbsolutePath(), 0, 595f,842f,"Hewlett-Packard HP LaserJet P2035",1); // // printPdf.print(); } catch (BadElementException | IOException ex) { Logger.getLogger(SeguroAPG.class.getName()).log(Level.SEVERE, null, ex); } catch (DocumentException ex) { Logger.getLogger(SeguroAPG.class.getName()).log(Level.SEVERE, null, ex); } return reString; }