List of usage examples for com.itextpdf.text Document newPage
public boolean newPage()
From source file:org.audiveris.omr.score.ui.BookPdfOutput.java
License:Open Source License
/** * Write the PDF output for the provided sheet if any, otherwise for the whole book. * * @param sheet desired sheet or null//from w ww . j ava2s. c o m * @throws Exception if printing goes wrong */ public void write(Sheet sheet) throws Exception { FileOutputStream fos = null; Document document = null; PdfWriter writer = null; try { final List<SheetStub> stubs = (sheet != null) ? Arrays.asList(sheet.getStub()) : book.getValidStubs(); fos = new FileOutputStream(file); for (SheetStub stub : stubs) { final int width = stub.getSheet().getWidth(); final int height = stub.getSheet().getHeight(); if (document == null) { document = new Document(new Rectangle(width, height)); writer = PdfWriter.getInstance(document, fos); document.open(); } else { document.setPageSize(new Rectangle(width, height)); document.newPage(); } PdfContentByte cb = writer.getDirectContent(); Graphics2D g2 = cb.createGraphics(width, height); // Scale: 1 g2.scale(1, 1); // Anti-aliasing ON g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Painting SheetResultPainter painter = new SheetResultPainter(stub.getSheet(), g2, false, // No voice painting true, // Paint staff lines false); // No annotations g2.setColor(Color.BLACK); painter.process(); // This is the end... g2.dispose(); } logger.info("Book printed to {}", file); } finally { if (document != null) { document.close(); } if (fos != null) { try { fos.close(); } catch (IOException ignored) { } } } }
From source file:org.gmdev.pdftrick.engine.MergeFiles.java
License:Open Source License
/** * Materially multiple pdf files are written merged file on a disk * @param list//from w w w . ja v a 2 s . co m * @param outputStream * @throws DocumentException * @throws IOException */ private void doMerge(List<StreamPwdContainer> list, OutputStream outputStream) throws DocumentException, IOException { HashMap<Integer, String> rotationFromPages = factory.getRotationFromPages(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfContentByte cb = writer.getDirectContent(); int z = 0; for (StreamPwdContainer boom : list) { InputStream in = boom.getIn(); PdfReader reader = null; if (!boom.getPwd().equalsIgnoreCase("")) { reader = new PdfReader(in, boom.getPwd().getBytes()); } else { reader = new PdfReader(in); } for (int i = 1; i <= reader.getNumberOfPages(); i++) { z++; int rotation = reader.getPageRotation(i); //set size Rectangle pageSize_ = reader.getPageSize(i); Rectangle pageSize = null; if (rotation == 270 || rotation == 90) { pageSize = new Rectangle(pageSize_.getHeight(), pageSize_.getWidth()); } else { pageSize = pageSize_; } document.setPageSize(pageSize); writer.setCropBoxSize(pageSize); document.newPage(); // import the page from source pdf PdfImportedPage page = writer.getImportedPage(reader, i); // add the page to the destination pdf if (rotation == 270) { cb.addTemplate(page, 0, 1.0f, -1.0f, 0, reader.getPageSizeWithRotation(i).getWidth(), 0); rotationFromPages.put(z, "" + rotation); } else if (rotation == 180) { cb.addTemplate(page, -1f, 0, 0, -1f, 0, 0); rotationFromPages.put(z, "" + rotation); } else if (rotation == 90) { cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight()); rotationFromPages.put(z, "" + rotation); } else { cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0); } } in.close(); } outputStream.flush(); document.close(); outputStream.close(); }
From source file:org.jaqpot.core.service.data.ReportService.java
public void report2PDF(Report report, OutputStream os) { Document document = new Document(); document.setPageSize(PageSize.A4);// ww w.j a va2 s . c o m document.setMargins(50, 45, 80, 40); document.setMarginMirroring(false); try { PdfWriter writer = PdfWriter.getInstance(document, os); TableHeader event = new TableHeader(); writer.setPageEvent(event); } catch (DocumentException ex) { throw new InternalServerErrorException(ex); } document.open(); /** setup fonts for pdf */ Font ffont = new Font(Font.FontFamily.UNDEFINED, 9, Font.ITALIC); Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLDITALIC); Font paragraphFontBold = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD); Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL); Font tableFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD); /** print link to jaqpot*/ Chunk chunk = new Chunk( "This report has been automatically created by the JaqpotQuatro report service. Click here to navigate to our official webpage", ffont); chunk.setAnchor("http://www.jaqpot.org"); Paragraph paragraph = new Paragraph(chunk); paragraph.add(Chunk.NEWLINE); Chapter chapter = new Chapter(paragraph, 1); chapter.setNumberDepth(0); /** get title */ String title = null; if (report.getMeta() != null && report.getMeta().getTitles() != null && !report.getMeta().getTitles().isEmpty()) title = report.getMeta().getTitles().iterator().next(); /** print title aligned centered in page */ if (title == null) title = "Report"; chunk = new Chunk(title, chapterFont); paragraph = new Paragraph(chunk); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.add(Chunk.NEWLINE); paragraph.add(Chunk.NEWLINE); chapter.add(paragraph); /** report Description */ if (report.getMeta() != null && report.getMeta().getDescriptions() != null && !report.getMeta().getDescriptions().isEmpty() && !report.getMeta().getDescriptions().toString().equalsIgnoreCase("null")) { paragraph = new Paragraph(); paragraph.add(new Chunk("Description: ", paragraphFontBold)); paragraph.add(new Chunk(report.getMeta().getDescriptions().toString().replaceAll(":http", ": http"), paragraphFont)); chapter.add(paragraph); chapter.add(Chunk.NEWLINE); } /** report model, algorithm and/or dataset id */ if (report.getMeta() != null && report.getMeta().getHasSources() != null && !report.getMeta().getHasSources().isEmpty() && !report.getMeta().getDescriptions().isEmpty() && !report.getMeta().getDescriptions().toString().equalsIgnoreCase("null")) { Iterator<String> sources = report.getMeta().getHasSources().iterator(); sources.forEachRemaining(o -> { if (o != null) { String[] source = o.split("/"); if (source[source.length - 2].trim().equals("model") || source[source.length - 2].trim().equals("algorithm") || source[source.length - 2].trim().equals("dataset")) { Paragraph paragraph1 = new Paragraph(); paragraph1.add(new Chunk(source[source.length - 2].substring(0, 1).toUpperCase() + source[source.length - 2].substring(1) + ": ", paragraphFontBold)); paragraph1.add(new Chunk(source[source.length - 1], paragraphFont)); chapter.add(paragraph1); chapter.add(Chunk.NEWLINE); } } }); } /** report single calculations */ report.getSingleCalculations().forEach((key, value) -> { Paragraph paragraph1 = new Paragraph(); paragraph1 = new Paragraph(); paragraph1.add(new Chunk(key + ": ", paragraphFontBold)); paragraph1.add(new Chunk(value.toString().trim().replaceAll(" +", " "), paragraphFont)); chapter.add(paragraph1); chapter.add(Chunk.NEWLINE); }); /** report date of completion */ if (report.getMeta() != null && report.getMeta().getDate() != null) { Paragraph paragraph1 = new Paragraph(); paragraph1.add(new Chunk("Procedure completed on: ", paragraphFontBold)); paragraph1.add(new Chunk(report.getMeta().getDate().toString(), paragraphFont)); chapter.add(paragraph1); chapter.add(Chunk.NEWLINE); } try { document.add(chapter); } catch (DocumentException ex) { throw new InternalServerErrorException(ex); } Integer chapterNumber = 0; /** report all_data */ for (Entry<String, ArrayCalculation> entry : report.getArrayCalculations().entrySet()) { String label = entry.getKey(); ArrayCalculation ac = entry.getValue(); PdfPTable table = new PdfPTable(ac.getColNames().size() + 1); for (Entry<String, List<Object>> row : ac.getValues().entrySet()) { try { XMLWorkerHelper.getInstance().parseXHtml(w -> { if (w instanceof WritableElement) { List<Element> elements = ((WritableElement) w).elements(); for (Element element : elements) { PdfPCell pdfCell = new PdfPCell(); pdfCell.addElement(element); table.addCell(pdfCell); } } }, new StringReader(row.getKey())); } catch (IOException e) { e.printStackTrace(); } for (Object o : row.getValue()) { table.addCell(o.toString()); } table.completeRow(); } try { Chunk tableChunk = new Chunk(label, tableFont); Chapter tableChapter = new Chapter(new Paragraph(tableChunk), ++chapterNumber); tableChapter.add(Chunk.NEWLINE); tableChapter.add(table); document.newPage(); document.add(tableChapter); } catch (DocumentException ex) { throw new InternalServerErrorException(ex); } } /** report plots */ for (Entry<String, String> entry : report.getFigures().entrySet()) { try { byte[] valueDecoded = Base64.decodeBase64(entry.getValue()); Image l = Image.getInstance(valueDecoded); document.newPage(); //image starts at the half's half of pdf page l.setAbsolutePosition(0, (document.getPageSize().getHeight() / 2 / 2)); l.scaleToFit(document.getPageSize()); Chunk tableChunk = new Chunk(entry.getKey(), tableFont); Chapter tableChapter = new Chapter(new Paragraph(tableChunk), ++chapterNumber); tableChapter.add(l); document.add(tableChapter); } catch (IOException | DocumentException e) { e.printStackTrace(); } } document.close(); }
From source file:org.javad.pdf.util.PdfUtil.java
License:Apache License
public static float findMaximumWidth(IContentGenerator generator, PdfContentByte content) { float width = 0.0f; try {//from w w w .j a v a 2 s. co m Document d = new Document(content.getPdfDocument().getPageSize()); PdfWriter writer = PdfWriter.getInstance(d, new ByteArrayOutputStream()); d.open(); PdfContentByte c = writer.getDirectContent(); OutputBounds bounds = generator.generate(c); width = bounds.width; d.newPage(); d.close(); } catch (Throwable e) { e.printStackTrace(); } return width; }
From source file:org.javad.stamp.pdf.PdfGenerator.java
License:Apache License
public void parseXMLDocument(GenerateBean bean, Document document, PdfWriter writer) throws Exception { document.open();//from w w w . ja v a2 s.com try { org.w3c.dom.Document xmlDoc = factory.getDocument(bean.getInputFile()); if (xmlDoc != null) { float boundsWidth = PdfUtil.convertFromMillimeters( config.getWidth() - config.getMarginLeft() - config.getMarginRight()); float center = (boundsWidth / 2.0f + PdfUtil.convertFromMillimeters(config.getMarginLeft())); NodeList albums = xmlDoc.getElementsByTagName(XMLDefinitions.ALBUM); if (albums != null && albums.getLength() > 0) { Element album = (Element) albums.item(0); NodeList pages = album.getChildNodes(); if (pages != null) { EventBus.publish(new StatusEvent(StatusType.MaximumProgress, pages.getLength())); if (bean.isReversePages()) { for (int p = pages.getLength() - 1; p >= 0; p--) { Element elm = (Element) pages.item(p); if (elm.getTagName().equals(XMLDefinitions.PAGE) || elm.getTagName().equals(XMLDefinitions.TITLE_PAGE)) { generatePage(bean, writer, center, elm, p - 1); if (p >= 0) { document.newPage(); } } } } else { for (int p = 0; p < pages.getLength(); p++) { Element elm = (Element) pages.item(p); if (elm.getTagName().equals(XMLDefinitions.PAGE) || elm.getTagName().equals(XMLDefinitions.TITLE_PAGE)) { generatePage(bean, writer, center, elm, p + 1); if (p < pages.getLength() - 1) { document.newPage(); } } } } } } NodeList titlePages = xmlDoc.getElementsByTagName(XMLDefinitions.TITLE_PAGE); } } catch (Exception t) { t.printStackTrace(); throw new RuntimeException(t); } finally { document.close(); } }
From source file:org.larz.dom4.editor.ReportGenerator.java
License:Open Source License
public static void generateReport(XtextEditor sourcePage, final Shell shell) { final IXtextDocument myDocument = ((XtextEditor) sourcePage).getDocument(); myDocument.modify(new IUnitOfWork.Void<XtextResource>() { @Override/*from www .j a va2s . com*/ public void process(XtextResource resource) throws Exception { Map<String, Map<String, ModObject>> cellMap = new HashMap<String, Map<String, ModObject>>(); Dom4Mod dom4Mod = (Dom4Mod) resource.getContents().get(0); EList<AbstractElement> elements = dom4Mod.getElements(); for (AbstractElement element : elements) { if (element instanceof SelectArmorById || element instanceof SelectArmorByName) { String name = getSelectArmorname((Armor) element); if (name == null) continue; String id = getArmorid((Armor) element); Map<String, ModObject> map = cellMap.get(ARMOR); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(ARMOR, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Armor) element, modObject.propertyMap); } else if (element instanceof NewArmor) { String name = getArmorname((Armor) element); String id = getArmorid((Armor) element); Map<String, ModObject> map = cellMap.get(ARMOR); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(ARMOR, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Armor) element, modObject.propertyMap); } else if (element instanceof SelectWeaponById || element instanceof SelectWeaponByName) { String name = getSelectWeaponname((Weapon) element); String id = getWeaponid((Weapon) element); Map<String, ModObject> map = cellMap.get(WEAPONS); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(WEAPONS, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Weapon) element, modObject.propertyMap); } else if (element instanceof NewWeapon) { String name = getWeaponname((Weapon) element); String id = getWeaponid((Weapon) element); Map<String, ModObject> map = cellMap.get(WEAPONS); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(WEAPONS, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Weapon) element, modObject.propertyMap); } else if (element instanceof SelectMonsterById || element instanceof SelectMonsterByName) { String name = getSelectMonstername((Monster) element); String id = getMonsterid((Monster) element); Map<String, ModObject> map = cellMap.get(MONSTERS); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(MONSTERS, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Monster) element, modObject.propertyMap); } else if (element instanceof NewMonster) { String name = getMonstername((Monster) element); String id = getMonsterid((Monster) element); Map<String, ModObject> map = cellMap.get(MONSTERS); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(MONSTERS, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Monster) element, modObject.propertyMap); } else if (element instanceof SelectSpellById || element instanceof SelectSpellByName) { String name = getSelectSpellname((Spell) element); String id = getSpellid((Spell) element); Map<String, ModObject> map = cellMap.get(SPELLS); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(SPELLS, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Spell) element, modObject.propertyMap); } else if (element instanceof NewSpell) { String name = getSpellname((Spell) element); //String id = getSpellid((Spell)element); Map<String, ModObject> map = cellMap.get(SPELLS); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(SPELLS, map); } ModObject modObject = map.get(name); if (modObject == null) { modObject = new ModObject(); modObject.title = "" + name; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(name, modObject); } setPropertyValues((Spell) element, modObject.propertyMap); } else if (element instanceof SelectItemById || element instanceof SelectItemByName) { String name = getSelectItemname((Item) element); String id = getItemid((Item) element); Map<String, ModObject> map = cellMap.get(ITEMS); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(ITEMS, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Item) element, modObject.propertyMap); } else if (element instanceof NewItem) { String name = getItemname((Item) element); //String id = getItemid((Item)element); Map<String, ModObject> map = cellMap.get(ITEMS); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(ITEMS, map); } ModObject modObject = map.get(name); if (modObject == null) { modObject = new ModObject(); modObject.title = name; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(name, modObject); } setPropertyValues((Item) element, modObject.propertyMap); } else if (element instanceof SelectSiteById || element instanceof SelectSiteByName) { String name = getSelectSitename((Site) element); String id = getSiteid((Site) element); Map<String, ModObject> map = cellMap.get(SITES); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(SITES, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Site) element, modObject.propertyMap); } else if (element instanceof NewSite) { String name = getSitename((Site) element); String id = getSiteid((Site) element); Map<String, ModObject> map = cellMap.get(SITES); if (map == null) { map = new HashMap<String, ModObject>(); cellMap.put(SITES, map); } ModObject modObject = map.get(id); if (modObject == null) { modObject = new ModObject(); modObject.title = name + " (" + id + ")"; modObject.propertyMap = new HashMap<String, PropertyValues>(); map.put(id, modObject); } setPropertyValues((Site) element, modObject.propertyMap); } else if (element instanceof SelectNation) { // String name = getSelectNationname((Nation)element); // String id = getNationid((Nation)element); // // Map<String, ModObject> map = cellMap.get(NATIONS); // if (map == null) { // map = new HashMap<String, ModObject>(); // cellMap.put(NATIONS, map); // } // ModObject modObject = map.get(id); // if (modObject == null) { // modObject = new ModObject(); // modObject.title = name + " (" + id + ")"; // modObject.propertyMap = new HashMap<String, PropertyValues>(); // map.put(id, modObject); // } // setPropertyValues((SelectNation)element, modObject.propertyMap, resource); } } try { // step 1 Document document = new Document(PageSize.LETTER.rotate()); // step 2 File tempFile = File.createTempFile("dom4editor", ".pdf"); tempFile.deleteOnExit(); FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile); PdfWriter.getInstance(document, tempFileOutputStream); // step 3 document.open(); List<Map.Entry<String, Map<String, ModObject>>> cellList = new ArrayList<Map.Entry<String, Map<String, ModObject>>>(); for (Map.Entry<String, Map<String, ModObject>> innerEntry : cellMap.entrySet()) { cellList.add(innerEntry); } Collections.sort(cellList, new Comparator<Map.Entry<String, Map<String, ModObject>>>() { @Override public int compare(Map.Entry<String, Map<String, ModObject>> o1, Map.Entry<String, Map<String, ModObject>> o2) { return o1.getKey().compareTo(o2.getKey()); } }); for (Map.Entry<String, Map<String, ModObject>> entry : cellList) { PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100f); PdfPCell cell = new PdfPCell(new Phrase(entry.getKey(), TITLE)); cell.setBackgroundColor(BaseColor.LIGHT_GRAY); cell.setFixedHeight(26f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); table.addCell(cell); table.setHeaderRows(1); List<Map.Entry<String, ModObject>> list = new ArrayList<Map.Entry<String, ModObject>>(); for (Map.Entry<String, ModObject> innerEntry : entry.getValue().entrySet()) { list.add(innerEntry); } Collections.sort(list, new Comparator<Map.Entry<String, ModObject>>() { @Override public int compare(Map.Entry<String, ModObject> o1, Map.Entry<String, ModObject> o2) { return o1.getValue().title.compareTo(o2.getValue().title); } }); PdfPTable propertyTable = null; if (entry.getKey().equals(ARMOR)) { propertyTable = getTable(new String[] { "name", "type", "prot", "def", "enc", "rcost" }, new String[] { "Name", "Type", "Prot", "Def", "Enc", "Rcost" }, new ValueTranslator[] { null, new ValueTranslator() { @Override public String translate(String value) { if (value == null) return null; if (value.equals("4")) return "Shield"; if (value.equals("5")) return "Body Armor"; if (value.equals("6")) return "Helmet"; return "Unknown"; } }, null, null, null, null }, null, list); propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1 }); } if (entry.getKey().equals(WEAPONS)) { propertyTable = getTable( new String[] { "name", "dmg", "att", "nratt", "def", "len", "range", "ammo", "rcost" }, new String[] { "Name", "Dmg", "Att", "Nratt", "Def", "Len", "Range", "Ammo", "Rcost" }, null, null, list); propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1, 1, 1, 1 }); } if (entry.getKey().equals(MONSTERS)) { propertyTable = getTable( new String[] { "name", "hp", "prot", "MOVE", "size", "ressize", "str", "enc", "att", "def", "prec", "mr", "mor", "gcost", "rcost" }, new String[] { "Name", "HP", "Prot", "Move", "Size", "Rsize", "Str", "Enc", "Att", "Def", "Prec", "MR", "Mor", "Gcost", "Rcost" }, null, new ValueCombiner[] { null, null, null, new ValueCombiner() { @Override public String translate(String[] value) { if (value[0] == null && value[1] == null) return null; return value[0] + "/" + value[1]; } @Override public String[] getNeededColumns() { return new String[] { "mapmove", "ap" }; } }, null, null, null, null, null, null, null, null, null, null, null }, list); propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }); } if (entry.getKey().equals(ITEMS)) { propertyTable = getTable( new String[] { "name", "constlevel", "PATH", "type", "weapon", "armor" }, new String[] { "Name", "Constlevel", "Path Req", "Type", "Weapon", "Armor" }, new ValueTranslator[] { null, null, null, new ValueTranslator() { @Override public String translate(String value) { if (value == null) return null; if (value.equals("1")) return "1-h Weapon"; if (value.equals("2")) return "2-h Weapon"; if (value.equals("3")) return "Missile Weapon"; if (value.equals("4")) return "Shield"; if (value.equals("5")) return "Body Armor"; if (value.equals("6")) return "Helmet"; if (value.equals("7")) return "Boots"; if (value.equals("8")) return "Misc"; return "Unknown"; } }, null, null }, new ValueCombiner[] { null, null, new ValueCombiner() { @Override public String translate(String[] value) { if (value[0] == null && value[1] == null && value[2] == null && value[3] == null) return null; StringBuffer buf = new StringBuffer(); if (value[0] != null && !value[0].equals("null")) { buf.append(getPathName(Integer.parseInt(value[0])) + value[1]); } if (value[2] != null && !value[2].equals("null") && !value[2].equals("-1")) { buf.append(getPathName(Integer.parseInt(value[2])) + value[3]); } return buf.toString(); } @Override public String[] getNeededColumns() { return new String[] { "mainpath", "mainlevel", "secondarypath", "secondarylevel" }; } }, null, null, null }, list); propertyTable.setWidths(new float[] { 2.5f, 1, 1, 1, 2.5f, 2.5f }); } if (entry.getKey().equals(SPELLS)) { propertyTable = getTable( new String[] { "name", "school", "researchlevel", "aoe", "damage", "effect", "fatiguecost", "nreff", "range", "precision", "spec", "nextspell" }, new String[] { "Name", "School", "Research", "AOE", "Damage", "Effect", "Fatigue", "Nreff", "Range", "Precision", "Spec", "Nextspell" }, null, null, list); propertyTable.setWidths(new float[] { 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }); } if (entry.getKey().equals(NATIONS)) { propertyTable = getTable(new String[] { "name", "startsite1", "startsite2", "startsite3", "startsite4", "era", "startfort" }, list); propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1, 1 }); } if (entry.getKey().equals(SITES)) { propertyTable = getTable( new String[] { "name", "path", "level", "rarity", "loc", "homemon", "homecom", "gold", "res" }, new String[] { "Name", "Path", "Level", "Rarity", "Loc", "Homemon", "Homecom", "Gold", "Res" }, new ValueTranslator[] { null, new ValueTranslator() { @Override public String translate(String value) { if (value == null) return null; if (value.equals("0")) return "Fire"; if (value.equals("1")) return "Air"; if (value.equals("2")) return "Water"; if (value.equals("3")) return "Earth"; if (value.equals("4")) return "Astral"; if (value.equals("5")) return "Death"; if (value.equals("6")) return "Nature"; if (value.equals("7")) return "Blood"; return "Unknown"; } }, null, null, null, null, null, null, null }, null, list); propertyTable.setWidths(new float[] { 5, 1, 1, 1, 1, 1, 1, 1, 1 }); } PdfPCell innerCell = new PdfPCell(); innerCell.addElement(propertyTable); innerCell.setBorder(PdfPCell.NO_BORDER); innerCell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(innerCell); document.add(table); document.newPage(); } document.close(); tempFileOutputStream.flush(); tempFileOutputStream.close(); Program pdfViewer = Program.findProgram("pdf"); if (pdfViewer != null) { pdfViewer.execute(tempFile.getAbsolutePath()); } else { FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterExtensions(new String[] { "*.pdf" }); if (dialog.open() != null) { FileInputStream from = null; FileOutputStream to = null; try { String filterPath = dialog.getFilterPath(); String name = dialog.getFileName(); from = new FileInputStream(new File(tempFile.getAbsolutePath())); to = new FileOutputStream(new File(filterPath + File.separator + name)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) { to.write(buffer, 0, bytesRead); // write } } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } } } } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:org.openscience.cdk.applications.taverna.basicutilities.ChartTool.java
License:Open Source License
/** * Writes given charts into target PDF file. * // w ww . java 2 s. c o m * @param file * @param charts * @param annotations * @throws IOException */ public synchronized void writeChartAsPDF(File file, List<Object> chartObjects) throws IOException { Rectangle pagesize = new Rectangle(this.width, this.height); Document document = new Document(pagesize, 50, 50, 50, 50); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.addAuthor("CDK-Taverna 2.0"); document.open(); PdfContentByte cb = writer.getDirectContent(); for (int i = 0; i < chartObjects.size(); i++) { Object obj = chartObjects.get(i); if (obj instanceof JFreeChart) { JFreeChart chart = (JFreeChart) obj; this.addChartPageToPDF(chart, cb); } else if (obj instanceof String) { String annotation = (String) obj; this.addAnnotationToPDF(annotation, document); } document.newPage(); } } catch (DocumentException e) { ErrorLogger.getInstance().writeError(CDKTavernaException.CANT_CREATE_PDF_FILE + file.getPath(), this.getClass().getSimpleName(), e); } document.close(); }
From source file:org.primaresearch.pdf.PageToPdfConverter.java
License:Apache License
/** * Adds a page to the PDF// www .ja v a 2 s . c o m * @param writer * @param doc * @param page * @param imageFile * @param addPageBreak */ private void addPage(PdfWriter writer, Document doc, Page page, String imageFile, boolean addPageBreak) { try { if (addPageBreak) { doc.setPageSize(new Rectangle(page.getLayout().getWidth(), page.getLayout().getHeight())); doc.newPage(); } //TODO Use image DPI and size //The measurement unit of the PDF is point (1 Point = 0.0352777778 cm) //For now: Set the PDF size to the PAGE size (1px = 1pt) //PDPage pdfPage = new PDPage(PDPage.PAGE_SIZE_A4); /*PDPage pdfPage = new PDPage(new PDRectangle(page.getLayout().getWidth(), page.getLayout().getHeight())); doc.addPage( pdfPage ); if (DEBUG) { System.out.println("Mediabox width: "+pdfPage.getMediaBox().getWidth()); System.out.println("Mediabox height: "+pdfPage.getMediaBox().getHeight()); } // Start a new content stream which will "hold" the to be created content PDPageContentStream contentStream = new PDPageContentStream(doc, pdfPage); */ try { addText(writer, page); addImage(imageFile, writer, doc, page); //The images hides the text if (addRegionOutlines) addOutlines(writer, page, null); if (addTextLineOutlines) addOutlines(writer, page, LowLevelTextType.TextLine); if (addWordOutlines) addOutlines(writer, page, LowLevelTextType.Word); if (addGlyphOutlines) addOutlines(writer, page, LowLevelTextType.Glyph); } finally { // Make sure that the content stream is closed: //contentStream.close(); } } catch (Exception exc) { exc.printStackTrace(); } }
From source file:org.saiku.web.export.PdfReport.java
License:Apache License
public byte[] pdf(QueryResult qr, String svg) throws Exception { int resultWidth = qr != null && qr.getCellset() != null && qr.getCellset().size() > 0 ? qr.getCellset().get(0).length : 0;/*from w ww . ja va2 s .c o m*/ if (resultWidth == 0) { throw new SaikuServiceException("Cannot convert empty result to PDF"); } Rectangle size = PageSize.A4.rotate(); if (resultWidth > 8) { size = PageSize.A3.rotate(); } if (resultWidth > 16) { size = PageSize.A2.rotate(); } if (resultWidth > 32) { size = PageSize.A1.rotate(); } if (resultWidth > 64) { size = PageSize.A0.rotate(); } Document document = new Document(size, 15, 15, 10, 10); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); populatePdf(document, writer, qr); // do we want to add a svg image? if (StringUtils.isNotBlank(svg)) { document.newPage(); StringBuffer s1 = new StringBuffer(svg); if (!svg.startsWith("<svg xmlns=\"http://www.w3.org/2000/svg\" ")) { s1.insert(s1.indexOf("<svg") + 4, " xmlns='http://www.w3.org/2000/svg'"); } String t = "<?xml version='1.0' encoding='ISO-8859-1'" + " standalone='no'?>" + s1.toString(); PdfContentByte cb = writer.getDirectContent(); cb.saveState(); cb.concatCTM(1.0f, 0, 0, 1.0f, 36, 0); float width = document.getPageSize().getWidth() - 20; float height = document.getPageSize().getHeight() - 20; Graphics2D g2 = cb.createGraphics(width, height); //g2.rotate(Math.toRadians(-90), 100, 100); PrintTranscoder prm = new PrintTranscoder(); TranscoderInput ti = new TranscoderInput(new StringReader(t)); prm.transcode(ti, null); PageFormat pg = new PageFormat(); Paper pp = new Paper(); pp.setSize(width, height); pp.setImageableArea(5, 5, width, height); pg.setPaper(pp); prm.print(g2, pg, 0); g2.dispose(); cb.restoreState(); } document.close(); return baos.toByteArray(); }
From source file:org.smap.sdal.managers.PDFSurveyManager.java
License:Open Source License
public String createPdf(OutputStream outputStream, String basePath, String serverRoot, String remoteUser, String language, boolean generateBlank, String filename, boolean landscape, // Set true if landscape HttpServletResponse response) throws Exception { if (language != null) { language = language.replace("'", "''"); // Escape apostrophes } else {/* w w w.ja v a 2 s. c om*/ language = "none"; } mExcludeEmpty = survey.exclude_empty; User user = null; ServerManager serverManager = new ServerManager(); ServerData serverData = serverManager.getServer(sd, localisation); UserManager um = new UserManager(localisation); int[] repIndexes = new int[20]; // Assume repeats don't go deeper than 20 levels Document document = null; PdfWriter writer = null; PdfReader reader = null; PdfStamper stamper = null; try { // Get fonts and embed them String os = System.getProperty("os.name"); log.info("Operating System:" + os); if (os.startsWith("Mac")) { FontFactory.register("/Library/Fonts/fontawesome-webfont.ttf", "Symbols"); //FontFactory.register("/Library/Fonts/Arial Unicode.ttf", "default"); FontFactory.register("/Library/Fonts/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/Library/Fonts/NotoSans-Regular.ttf", "notosans"); FontFactory.register("/Library/Fonts/NotoSans-Bold.ttf", "notosansbold"); FontFactory.register("/Library/Fonts/NotoSansBengali-Regular.ttf", "bengali"); FontFactory.register("/Library/Fonts/NotoSansBengali-Bold.ttf", "bengalibold"); } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) { // Linux / Unix FontFactory.register("/usr/share/fonts/truetype/fontawesome-webfont.ttf", "Symbols"); FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans"); FontFactory.register("/usr/share/fonts/truetype/NotoSans-Bold.ttf", "notosansbold"); FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Regular.ttf", "bengali"); FontFactory.register("/usr/share/fonts/truetype/NotoSansBengali-Bold.ttf", "bengalibold"); } Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); defaultFontLink = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); defaultFont = FontFactory.getFont("notosans", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); defaultFontBold = FontFactory.getFont("notosansbold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); arabicFont = FontFactory.getFont("arabic", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); bengaliFont = FontFactory.getFont("bengali", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); bengaliFontBold = FontFactory.getFont("bengalibold", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); defaultFontLink.setColor(BaseColor.BLUE); /* * Get the results and details of the user that submitted the survey */ log.info("User Ident who submitted the survey: " + survey.instance.user); String userName = survey.instance.user; if (userName == null) { userName = remoteUser; } if (userName != null) { user = um.getByIdent(sd, userName); } // If a filename was not specified then get one from the survey data // This filename is returned to the calling program so that it can be used as a permanent name for the temporary file created here // If the PDF is to be returned in an http response then the header is set now before writing to the output stream log.info("Filename passed to createPDF is: " + filename); if (filename == null) { filename = survey.getInstanceName() + ".pdf"; } else { if (!filename.endsWith(".pdf")) { filename += ".pdf"; } } // If the PDF is to be returned in an http response then set the file name now if (response != null) { log.info("Setting filename to: " + filename); GeneralUtilityMethods.setFilenameInResponse(filename, response); } /* * Get a template for the PDF report if it exists * The template name will be the same as the XLS form name but with an extension of pdf */ File templateFile = GeneralUtilityMethods.getPdfTemplate(basePath, survey.displayName, survey.p_id); /* * Get dependencies between Display Items, for example if a question result should be added to another * question's results */ GlobalVariables gv = new GlobalVariables(); if (!generateBlank) { for (int i = 0; i < survey.instance.results.size(); i++) { getDependencies(gv, survey.instance.results.get(i), survey, i); } } gv.mapbox_key = serverData.mapbox_default; int oId = GeneralUtilityMethods.getOrganisationId(sd, remoteUser); languageIdx = GeneralUtilityMethods.getLanguageIdx(survey, language); if (templateFile.exists()) { log.info("PDF Template Exists"); String templateName = templateFile.getAbsolutePath(); reader = new PdfReader(templateName); stamper = new PdfStamper(reader, outputStream); for (int i = 0; i < survey.instance.results.size(); i++) { fillTemplate(gv, stamper.getAcroFields(), survey.instance.results.get(i), basePath, null, i, serverRoot, stamper, oId); } if (user != null) { fillTemplateUserDetails(stamper.getAcroFields(), user, basePath); } stamper.setFormFlattening(true); } else { log.info("++++No template exists creating a pdf file programmatically"); /* * Create a PDF without the stationary * If we need to add a letter head then create document in two passes, the second pass adds the letter head * Else just create the document directly in a single pass */ Parser parser = getXMLParser(); // Step 1 - Create the underlying document as a byte array if (landscape) { document = new Document(PageSize.A4.rotate()); } else { document = new Document(PageSize.A4); } document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1); writer = PdfWriter.getInstance(document, outputStream); writer.setInitialLeading(12); writer.setPageEvent(new PdfPageSizer(survey.displayName, survey.projectName, user, basePath, null, marginLeft, marginRight, marginTop_2, marginBottom_2)); document.open(); // If this form has data maintain a list of parent records to lookup ${values} ArrayList<ArrayList<Result>> parentRecords = null; if (!generateBlank) { parentRecords = new ArrayList<ArrayList<Result>>(); } for (int i = 0; i < survey.instance.results.size(); i++) { processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot, generateBlank, 0, i, repIndexes, gv, false, parentRecords, remoteUser, oId); } fillNonTemplateUserDetails(document, user, basePath); // Add appendix if (gv.hasAppendix) { document.newPage(); document.add(new Paragraph("Appendix", defaultFontBold)); for (int i = 0; i < survey.instance.results.size(); i++) { processForm(parser, document, survey.instance.results.get(i), basePath, serverRoot, generateBlank, 0, i, repIndexes, gv, true, parentRecords, remoteUser, oId); } } } } finally { if (document != null) try { document.close(); } catch (Exception e) { } ; if (writer != null) try { writer.close(); } catch (Exception e) { } ; if (stamper != null) try { stamper.close(); } catch (Exception e) { } ; if (reader != null) try { reader.close(); } catch (Exception e) { } ; } return filename; }