List of usage examples for com.itextpdf.text.pdf BaseFont IDENTITY_H
String IDENTITY_H
To view the source code for com.itextpdf.text.pdf BaseFont IDENTITY_H.
Click Source Link
From source file:org.alfresco.repo.content.transform.ITextPDFWorker.java
License:Apache License
/** * Obtains the base arial unicode font, contained in the war. * * @return the created and registered base font *//*from w ww .j a v a2 s . c o m*/ private static BaseFont getBaseFont() { try { InputStream resourceAsStream = ITextPDFWorker.class.getResourceAsStream(ARIAL_TTF); File tempDir = TempFileProvider.getSystemTempDir(); File tempFontFile = new File(tempDir, ARIAL_TTF); if (!tempFontFile.exists() || !tempFontFile.canRead()) { FileOutputStream fileOutputStream = new FileOutputStream(tempFontFile.getAbsoluteFile()); IOUtils.copy(resourceAsStream, fileOutputStream); IOUtils.closeQuietly(fileOutputStream); } FontFactory.register(tempFontFile.getAbsolutePath()); return BaseFont.createFont(tempFontFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); } catch (Exception e) { e.printStackTrace(); try { return BaseFont.createFont(); } catch (Exception e1) { // shouldn't occur ever e1.printStackTrace(); } } return null; }
From source file:org.allcolor.yahp.cl.converter.CHtmlToPdfFlyingSaucerTransformer.java
License:Open Source License
private static void registerTTF(final File f, final _ITextRenderer renderer) { if (f.isDirectory()) { final File[] list = f.listFiles(); if (list != null) { for (int i = 0; i < list.length; i++) { CHtmlToPdfFlyingSaucerTransformer.registerTTF(list[i], renderer); }/*from w w w . j a v a2 s . c om*/ } } else if (CHtmlToPdfFlyingSaucerTransformer.accept(f.getParentFile(), f.getName())) { if (!renderer.isKnown(f.getAbsolutePath())) { /*InputStream in = null; try { in = f.toURI().toURL().openStream(); GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(Font.createFont(Font.TRUETYPE_FONT, in)); } catch (final Throwable ignore) { } finally { try { if (in != null) { in.close(); } } catch (final Exception ignore) { } }*/ try { renderer.getFontResolver().addFont(f.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); renderer.addKnown(f.getAbsolutePath()); } catch (final Throwable ignore) { } } } }
From source file:org.cherchgk.actions.tournament.result.show.GetPDFTournamentResultAction.java
License:Apache License
private BaseFont getBaseFont(String fontFileName) { String realPath = ActionContextHelper.getRequest().getSession().getServletContext().getRealPath(""); String realFontFileName = realPath + File.separator + "WEB-INF" + File.separator + "fonts" + File.separator + fontFileName;//from w ww.j av a 2 s . c o m try { return BaseFont.createFont(realFontFileName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); } catch (DocumentException e) { log.log(Level.SEVERE, "Can't read " + realFontFileName, e); return null; } catch (IOException e) { log.log(Level.SEVERE, "Can't read " + realFontFileName, e); return null; } }
From source file:org.h819.commons.file.MyPDFUtils.java
/** * STCAIYUN.TTF?? jar? classpath/*from w w w .j a v a 2 s . c om*/ * ? pdf ??? pdf ? * ?????? * * @return * @throws IOException */ private static Font getPdfFont() { // String fontName = "/STCAIYUN.TTF"; String fontPath = SystemUtils.getJavaIoTmpDir() + File.separator + MyConstants.JarTempDir + File.separator + fontName; //????? if (!Files.exists(Paths.get(fontPath))) { MyFileUtils.copyResourceFileFromJarLibToTmpDir(fontName); } return FontFactory.getFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); }
From source file:org.javad.pdf.fonts.FontRegistry.java
License:Apache License
/** * This method will attempt to find the named font with the specified size and style * using a naming roll-off technique based on some of the naming conventions observed. * <ul><li>//w w w . j a va2s.c o m * If the style is bold and italic, a font with the name <code>"[name]-bolditalic"</code> * will attempted. </li> * <li>If the style is both a name like <code>"[name] bold"</code> will be * attempted.</li> * <li>If the font is italic, the names <code>"[name] italic"</code> and then * <code>"[name]-italic"</code> will be tried.</li> * <li> Finally if none of these styled fonts can be located, the <code>"[name]"</code> will be tried.</li> * </ul> * * @param name * @param bean * @return */ Font findFont(String name, PdfFontBean bean) { String form = (bean.isI18N()) ? BaseFont.IDENTITY_H : BaseFont.CP1252; Font f = null; if (bean.isBold() && bean.isItalic()) { f = FontFactory.getFont(name + "-bolditalic", form, bean.getSize(), bean.getStyle()); } if (isFontInvalid(f) && bean.isBold()) { f = FontFactory.getFont(name + " bold", form, bean.getSize(), bean.getStyle()); } if (isFontInvalid(f) && bean.isItalic()) { f = FontFactory.getFont(name + " italic", form, bean.getSize(), bean.getStyle()); if (isFontInvalid(f)) { f = FontFactory.getFont(name + "-italic", form, bean.getSize(), bean.getStyle()); } } if (isFontInvalid(f)) { f = FontFactory.getFont(name, form, bean.getSize(), bean.getStyle()); } if (logger.isLoggable(Level.FINER)) { @SuppressWarnings("null") BaseFont bf = f.getBaseFont(); if (bf != null) { String[][] fullName = bf.getFullFontName(); if (fullName != null && fullName.length >= 1 && fullName[0].length >= 4) { logger.log(Level.FINER, "The calculated font name is \"{0}\"", fullName[0][3]); } else { logger.finer("The base font full name was not parseable."); } } else { logger.log(Level.FINER, "The base font was null for \"{0}\" with style {1}", new Object[] { name, bean.getStyle() }); } } return f; }
From source file:org.primaresearch.pdf.PageToPdfConverter.java
License:Apache License
/** * Creates the font that is to be used for the hidden text layer in the PDF. *//*w ww.ja v a2 s . c om*/ private void createFont() throws DocumentException, IOException { //TODO Even with the 'NOT_EMBEDDED' settings it seems to embed the font! if (ttfFontFilePath == null) font = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); else { font = FontFactory.getFont(ttfFontFilePath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED).getBaseFont(); //PDTrueTypeFont.loadTTF(document, ttfFontFilePath); //Encoding enc = font.getFontEncoding(); //Map<Integer, String> map = enc.getCodeToNameMap(); //System.out.println("Font encoding map size: " + map.size()); } }
From source file:org.qnot.passtab.PDFOutput.java
License:Open Source License
public PDFOutput(boolean withColor) { this.withColor = withColor; try {/* w ww . j a v a 2 s . com*/ font = new Font(BaseFont.createFont(PDFOutput.FONT_MONOSPACE, BaseFont.IDENTITY_H, BaseFont.EMBEDDED)); fontBold = new Font( BaseFont.createFont(PDFOutput.FONT_MONOSPACE_BOLD, BaseFont.IDENTITY_H, BaseFont.EMBEDDED)); } catch (Exception e) { try { font = new Font(BaseFont.createFont()); fontBold = new Font(BaseFont.createFont()); } catch (Exception ignored) { } } font.setSize(DEFAULT_FONT_SIZE); fontBold.setSize(DEFAULT_FONT_SIZE); }
From source file:org.smap.sdal.managers.MiscPDFManager.java
License:Open Source License
public void createUsagePdf(Connection sd, OutputStream outputStream, String basePath, HttpServletResponse response, int o_id, int month, int year, String period, String org_name) { PreparedStatement pstmt = null; if (org_name == null) { org_name = "None"; }// w w w . ja va 2s.c om try { String filename; // 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"); } 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/ttf-dejavu/DejaVuSans.ttf", "default"); FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans"); } Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); filename = org_name + "_" + year + "_" + month + ".pdf"; /* * Get the usage results */ String sql = "SELECT users.id as id," + "users.ident as ident, " + "users.name as name, " + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id " + "and se.status = 'success' " + "and se.subscriber = 'results_db' " + "and extract(month from upload_time) = ? " // current month + "and extract(year from upload_time) = ? " // current year + "and ue.user_name = users.ident) as month, " + "(select count (*) from upload_event ue, subscriber_event se " + "where ue.ue_id = se.ue_id " + "and se.status = 'success' " + "and se.subscriber = 'results_db' " + "and ue.user_name = users.ident) as all_time " + "from users " + "where users.o_id = ? " + "and not users.temporary " + "order by users.ident;"; pstmt = sd.prepareStatement(sql); pstmt.setInt(1, month); pstmt.setInt(2, year); pstmt.setInt(3, o_id); log.info("Get Usage Data: " + pstmt.toString()); // 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); 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 */ String stationaryName = basePath + File.separator + "misc" + File.separator + "UsageReportTemplate.pdf"; File stationaryFile = new File(stationaryName); ByteArrayOutputStream baos = null; ByteArrayOutputStream baos_s = null; PdfWriter writer = null; /* * Create document in two passes, the second pass adds the letter head */ // Create the underlying document as a byte array Document document = new Document(PageSize.A4); document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1); if (stationaryFile.exists()) { baos = new ByteArrayOutputStream(); baos_s = new ByteArrayOutputStream(); writer = PdfWriter.getInstance(document, baos); } else { writer = PdfWriter.getInstance(document, outputStream); } writer.setInitialLeading(12); writer.setPageEvent(new PageSizer()); document.open(); // Write the usage data ResultSet resultSet = pstmt.executeQuery(); PdfPTable table = new PdfPTable(4); // Add the header row table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY); table.getDefaultCell().setBackgroundColor(VLG); table.addCell("User Id"); table.addCell("User Name"); table.addCell("Usage in Period"); table.addCell("All Time Usage"); table.setHeaderRows(1); // Add the user data int total = 0; int totalAllTime = 0; table.getDefaultCell().setBackgroundColor(null); while (resultSet.next()) { String ident = resultSet.getString("ident"); String name = resultSet.getString("name"); String monthUsage = resultSet.getString("month"); int monthUsageInt = resultSet.getInt("month"); String allTime = resultSet.getString("all_time"); int allTimeInt = resultSet.getInt("all_time"); table.addCell(ident); table.addCell(name); table.addCell(monthUsage); table.addCell(allTime); total += monthUsageInt; totalAllTime += allTimeInt; } // Add the totals table.getDefaultCell().setBackgroundColor(VLG); table.addCell("Totals: "); table.addCell(" "); table.addCell(String.valueOf(total)); table.addCell(String.valueOf(totalAllTime)); document.add(table); document.close(); if (stationaryFile.exists()) { // Step 2 - Populate the fields in the stationary PdfReader s_reader = new PdfReader(stationaryName); PdfStamper s_stamper = new PdfStamper(s_reader, baos_s); AcroFields pdfForm = s_stamper.getAcroFields(); Set<String> fields = pdfForm.getFields().keySet(); for (String key : fields) { log.info("Field: " + key); } pdfForm.setField("billing_period", period); pdfForm.setField("organisation", org_name); s_stamper.setFormFlattening(true); s_stamper.close(); // Step 3 - Apply the stationary to the underlying document PdfReader reader = new PdfReader(baos.toByteArray()); // Underlying document PdfReader f_reader = new PdfReader(baos_s.toByteArray()); // Filled in stationary PdfStamper stamper = new PdfStamper(reader, outputStream); PdfImportedPage letter1 = stamper.getImportedPage(f_reader, 1); int n = reader.getNumberOfPages(); PdfContentByte background; for (int i = 0; i < n; i++) { background = stamper.getUnderContent(i + 1); if (i == 0) { background.addTemplate(letter1, 0, 0); } } stamper.close(); reader.close(); } } catch (SQLException e) { log.log(Level.SEVERE, "SQL Error", e); } catch (Exception e) { log.log(Level.SEVERE, "Exception", e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } }
From source file:org.smap.sdal.managers.MiscPDFManager.java
License:Open Source License
public void createTasksPdf(Connection sd, OutputStream outputStream, String basePath, HttpServletRequest request, HttpServletResponse response, int tgId) { try {// w w w.j a va 2 s.c om // 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"); } 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/ttf-dejavu/DejaVuSans.ttf", "default"); FontFactory.register("/usr/share/fonts/truetype/NotoNaskhArabic-Regular.ttf", "arabic"); FontFactory.register("/usr/share/fonts/truetype/NotoSans-Regular.ttf", "notosans"); } Symbols = FontFactory.getFont("Symbols", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12); defaultFont = FontFactory.getFont("default", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10); /* * Get the tasks for this task group */ String urlprefix = request.getScheme() + "://" + request.getServerName(); TaskManager tm = new TaskManager(localisation, tz); TaskListGeoJson t = tm.getTasks(sd, urlprefix, 0, tgId, 0, false, 0, null, "all", 0, 0, "scheduled", "desc"); PdfWriter writer = null; String filename = "tasks.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); setFilenameInResponse(filename, response); } Document document = new Document(PageSize.A4); document.setMargins(marginLeft, marginRight, marginTop_1, marginBottom_1); writer = PdfWriter.getInstance(document, outputStream); writer.setInitialLeading(12); writer.setPageEvent(new PageSizer()); document.open(); PdfPTable table = new PdfPTable(4); // Add the header row table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY); table.getDefaultCell().setBackgroundColor(VLG); table.addCell("Form Name"); table.addCell("Task Name"); table.addCell("Status"); table.addCell("Assigned To"); table.setHeaderRows(1); // Add the task data table.getDefaultCell().setBackgroundColor(null); for (TaskFeature tf : t.features) { TaskProperties p = tf.properties; table.addCell(p.survey_name); table.addCell(p.name); table.addCell(p.status); table.addCell(p.assignee_name); } document.add(table); document.close(); } catch (SQLException e) { log.log(Level.SEVERE, "SQL Error", e); } catch (Exception e) { log.log(Level.SEVERE, "Exception", e); } }
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 {//www. j a v a 2s.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; }