public virtual void StandardFontForceEmbeddedTest() { Type1Font fontProgram = (Type1Font)FontProgramFactory.CreateFont(StandardFonts.HELVETICA); NUnit.Framework.Assert.That(() => { PdfFontFactory.CreateFont(fontProgram, PdfEncodings.UTF8, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED); } , NUnit.Framework.Throws.InstanceOf <PdfException>().With.Message.EqualTo(PdfException.CannotEmbedStandardFont)) ; }
/// <summary> /// Creates the PDF file. /// </summary> /// <param name="src">the path to the source HTML file</param> /// <param name="font">the path to an extra font</param> /// <param name="dest">the path to the resulting PDF</param> public void CreatePdf(String src, String font, String dest) { ConverterProperties properties = new ConverterProperties(); FontProvider fontProvider = new DefaultFontProvider(); FontProgram fontProgram = FontProgramFactory.CreateFont(font); fontProvider.AddFont(fontProgram); properties.SetFontProvider(fontProvider); HtmlConverter.ConvertToPdf(new FileInfo(src), new FileInfo(dest), properties); }
public virtual void TestLookupFlagWithMarkAttachmentTypeAndBaseGlyph() { String fontName = "Padauk-Regular.ttf"; TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + fontName); OpenTypeGdefTableReader gdef = fontProgram.GetGdefTable(); int glyphCode = 165; NUnit.Framework.Assert.AreEqual(OtfClass.GLYPH_BASE, gdef.GetGlyphClassTable().GetOtfClass(glyphCode)); NUnit.Framework.Assert.IsFalse(gdef.IsSkip(glyphCode, (1 << 8))); }
public virtual void ComparatorErrorTest() { // TODO: DEVSIX-4017 (Combination of default and pdfCalligraph fonts with italic style and '"courier new", courier, // monospace' family reproduces comparator exception. Update test after fixing.) ConverterProperties properties = new ConverterProperties(); FontProvider pro = new DefaultFontProvider(); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSansArabic-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSansArabic-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSansGurmukhi-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSansGurmukhi-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSansMyanmar-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSansMyanmar-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSansOriya-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSansOriya-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifBengali-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifBengali-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifDevanagari-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifDevanagari-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifGujarati-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifGujarati-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifHebrew-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifHebrew-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifKannada-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifKannada-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifKhmer-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifKhmer-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifMalayalam-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifMalayalam-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifMyanmar-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifMyanmar-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifTamil-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifTamil-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifTelugu-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifTelugu-Bold.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifThai-Regular.ttf")); pro.AddFont(FontProgramFactory.CreateFont(SOURCE_FOLDER + "NotoSerifThai-Bold.ttf")); properties.SetFontProvider(pro); bool isExceptionThrown = false; try { HtmlConverter.ConvertToPdf(new FileInfo(SOURCE_FOLDER + "comparatorError.html"), new FileInfo(DESTINATION_FOLDER + "comparatorError.pdf"), properties); } catch (ArgumentException e) { NUnit.Framework.Assert.AreEqual("Comparison method violates its general contract!", e.Message); isExceptionThrown = true; } if (!isExceptionThrown) { NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(DESTINATION_FOLDER + "comparatorError.pdf" , SOURCE_FOLDER + "cmp_comparatorError.pdf", DESTINATION_FOLDER)); } }
/// <summary> /// Get from cache or create a new instance of /// <see cref="iText.Kernel.Font.PdfFont"/> /// . /// </summary> /// <param name="fontInfo"> /// font info, to create /// <see cref="iText.IO.Font.FontProgram"/> /// and /// <see cref="iText.Kernel.Font.PdfFont"/> /// . /// </param> /// <param name="tempFonts">Set of temporary fonts.</param> /// <returns> /// cached or new instance of /// <see cref="iText.Kernel.Font.PdfFont"/> /// . /// </returns> public virtual PdfFont GetPdfFont(FontInfo fontInfo, FontSet tempFonts) { if (pdfFonts.ContainsKey(fontInfo)) { return(pdfFonts.Get(fontInfo)); } else { FontProgram fontProgram = null; if (tempFonts != null) { fontProgram = tempFonts.GetFontProgram(fontInfo); } if (fontProgram == null) { fontProgram = fontSet.GetFontProgram(fontInfo); } PdfFont pdfFont; try { if (fontProgram == null) { if (fontInfo.GetFontData() != null) { fontProgram = FontProgramFactory.CreateFont(fontInfo.GetFontData(), GetDefaultCacheFlag()); } else { fontProgram = FontProgramFactory.CreateFont(fontInfo.GetFontName(), GetDefaultCacheFlag()); } } String encoding = fontInfo.GetEncoding(); if (encoding == null || encoding.Length == 0) { encoding = GetDefaultEncoding(fontProgram); } pdfFont = PdfFontFactory.CreateFont(fontProgram, encoding, GetDefaultEmbeddingFlag()); } catch (System.IO.IOException e) { // Converting checked exceptions to unchecked RuntimeException (java-specific comment). // // FontProvider is usually used in highlevel API, which requests fonts in deep underlying logic. // IOException would mean that font is chosen and it is supposed to exist, however it cannot be read. // Using fallbacks in such situations would make FontProvider less intuitive. // // Even though softening of checked exceptions can be handled at higher levels in order to let // the caller of this method know that font creation failed, we prefer to avoid bloating highlevel API // and avoid making higher level code depend on low-level code because of the exceptions handling. throw new PdfException(PdfException.IoExceptionWhileCreatingFont, e); } pdfFonts.Put(fontInfo, pdfFont); return(pdfFont); } }
public virtual void VerifyXAdvanceIsAppliedForContextualPositioning() { TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoSansMyanmar-Regular.ttf" ); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType7 lookup = (GposLookupType7)gposTableReader.GetLookupTable(28); IList <Glyph> glyphs = JavaUtil.ArraysAsList(fontProgram.GetGlyphByCode(25), fontProgram.GetGlyphByCode(174 ), fontProgram.GetGlyphByCode(5), fontProgram.GetGlyphByCode(411)); GlyphLine gl = new GlyphLine(glyphs); NUnit.Framework.Assert.AreEqual(0, gl.Get(1).GetXAdvance()); NUnit.Framework.Assert.IsTrue(lookup.TransformLine(gl)); NUnit.Framework.Assert.AreEqual(219, gl.Get(1).GetXAdvance()); }
public virtual void VerifyPositionIsNotAppliedForIrrelevantGlyph() { TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoSansMyanmar-Regular.ttf" ); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType1 lookup = (GposLookupType1)gposTableReader.GetLookupTable(29); IList <Glyph> glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(5)), new Glyph(fontProgram .GetGlyphByCode(174))); GlyphLine gl = new GlyphLine(glyphs); gl.idx = 0; NUnit.Framework.Assert.AreEqual(0, gl.Get(0).GetXAdvance()); NUnit.Framework.Assert.IsFalse(lookup.TransformOne(gl)); NUnit.Framework.Assert.AreEqual(0, gl.Get(0).GetXAdvance()); }
public virtual void VerifyMarkToBaseAttachment() { TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "KhmerOS.ttf"); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType5 lookup = (GposLookupType5)gposTableReader.GetLookupTable(0); IList <Glyph> glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(445)), new Glyph(fontProgram .GetGlyphByCode(394))); GlyphLine gl = new GlyphLine(glyphs); gl.idx = 1; lookup.TransformOne(gl); NUnit.Framework.Assert.AreEqual(2, gl.Size()); NUnit.Framework.Assert.AreEqual(445, gl.Get(0).GetCode()); NUnit.Framework.Assert.AreEqual(394, gl.Get(1).GetCode()); NUnit.Framework.Assert.AreEqual(-1, gl.Get(1).GetAnchorDelta()); NUnit.Framework.Assert.AreEqual(756, gl.Get(1).GetXPlacement()); }
public virtual void TestThatNoTransformationsAppliedForNonRelevantGlyphs() { TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoNaskhArabic-Regular.ttf" ); GlyphLine glyphLine = new GlyphLine(JavaUtil.ArraysAsList(fontProgram.GetGlyph('1'), fontProgram.GetGlyphByCode (75))); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType5 lookup = (GposLookupType5)gposTableReader.GetLookupTable(3); glyphLine.idx = 1; lookup.TransformOne(glyphLine); NUnit.Framework.Assert.AreEqual(2, glyphLine.Size()); NUnit.Framework.Assert.AreEqual(1490, glyphLine.Get(0).GetCode()); NUnit.Framework.Assert.AreEqual(75, glyphLine.Get(1).GetCode()); NUnit.Framework.Assert.AreEqual(0, glyphLine.Get(1).GetAnchorDelta()); NUnit.Framework.Assert.AreEqual(0, glyphLine.Get(1).GetXPlacement()); }
public virtual void TestFetchLangSysByTag() { TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoSansMyanmar-Regular.ttf" ); GlyphSubstitutionTableReader gsub = fontProgram.GetGsubTable(); ScriptRecord mym2 = gsub.GetScriptRecords()[0]; NUnit.Framework.Assert.AreEqual("mym2", mym2.tag); // default LangSys has no tag NUnit.Framework.Assert.AreEqual("", gsub.GetLanguageRecord("mym2").tag); NUnit.Framework.Assert.AreEqual(LanguageTags.SGAW_KAREN, gsub.GetLanguageRecord("mym2", LanguageTags.SGAW_KAREN ).tag); NUnit.Framework.Assert.AreEqual(LanguageTags.MON, gsub.GetLanguageRecord("mym2", LanguageTags.MON).tag); NUnit.Framework.Assert.IsNull(gsub.GetLanguageRecord(null)); NUnit.Framework.Assert.IsNull(gsub.GetLanguageRecord("mym3")); NUnit.Framework.Assert.IsNull(gsub.GetLanguageRecord("mym3", LanguageTags.SGAW_KAREN)); }
public virtual void VerifyMarkToBaseAttachment() { TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "Padauk-Regular.ttf" ); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType4 lookup = (GposLookupType4)gposTableReader.GetLookupTable(192); IList <Glyph> glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(163)), new Glyph(fontProgram .GetGlyphByCode(207)), new Glyph(fontProgram.GetGlyphByCode(213))); GlyphLine gl = new GlyphLine(glyphs); gl.idx = 2; NUnit.Framework.Assert.AreEqual(0, gl.Get(2).GetXPlacement()); NUnit.Framework.Assert.AreEqual(0, gl.Get(2).GetAnchorDelta()); lookup.TransformOne(gl); NUnit.Framework.Assert.AreEqual(364, gl.Get(2).GetXPlacement()); NUnit.Framework.Assert.AreEqual(-2, gl.Get(2).GetAnchorDelta()); }
/// <summary>Creates a font and adds it to the context.</summary> /// <param name="fontFamily">the font family</param> /// <param name="src">the source of the font</param> /// <returns>true, if successful</returns> private bool CreateFont(String fontFamily, FontFace.FontFaceSrc src) { if (!SupportedFontFormat(src.format)) { return(false); } else { if (src.isLocal) { // to method with lazy initialization ICollection <FontInfo> fonts = context.GetFontProvider().GetFontSet().Get(src.src); if (fonts.Count > 0) { foreach (FontInfo fi in fonts) { context.AddTemporaryFont(fi, fontFamily); } // return(true); } else { return(false); } } else { try { // Cache at resource resolver level only, at font level we will create font in any case. // The instance of fontProgram will be collected by GC if the is no need in it. byte[] bytes = context.GetResourceResolver().RetrieveBytesFromResource(src.src); if (bytes != null) { FontProgram fp = FontProgramFactory.CreateFont(bytes, false); context.AddTemporaryFont(fp, PdfEncodings.IDENTITY_H, fontFamily); return(true); } } catch (Exception) { } return(false); } } }
/// <summary> /// Get from cache or create a new instance of /// <see cref="iText.Kernel.Font.PdfFont"/> /// . /// </summary> /// <param name="fontInfo"> /// font info, to create /// <see cref="iText.IO.Font.FontProgram"/> /// and /// <see cref="iText.Kernel.Font.PdfFont"/> /// . /// </param> /// <param name="tempFonts">Set of temporary fonts.</param> /// <returns> /// cached or new instance of /// <see cref="iText.Kernel.Font.PdfFont"/> /// . /// </returns> public virtual PdfFont GetPdfFont(FontInfo fontInfo, FontSet tempFonts) { if (pdfFonts.ContainsKey(fontInfo)) { return(pdfFonts.Get(fontInfo)); } else { FontProgram fontProgram = null; if (tempFonts != null) { fontProgram = tempFonts.GetFontProgram(fontInfo); } if (fontProgram == null) { fontProgram = fontSet.GetFontProgram(fontInfo); } PdfFont pdfFont; try { if (fontProgram == null) { if (fontInfo.GetFontData() != null) { fontProgram = FontProgramFactory.CreateFont(fontInfo.GetFontData(), GetDefaultCacheFlag()); } else { fontProgram = FontProgramFactory.CreateFont(fontInfo.GetFontName(), GetDefaultCacheFlag()); } } String encoding = fontInfo.GetEncoding(); if (encoding == null || encoding.Length == 0) { encoding = GetDefaultEncoding(fontProgram); } pdfFont = PdfFontFactory.CreateFont(fontProgram, encoding, GetDefaultEmbeddingFlag()); } catch (System.IO.IOException e) { throw new PdfException(PdfException.IoExceptionWhileCreatingFont, e); } pdfFonts.Put(fontInfo, pdfFont); return(pdfFont); } }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); PdfCanvas under = new PdfCanvas(pdfDoc.GetFirstPage().NewContentStreamBefore(), new PdfResources(), pdfDoc); PdfFont font = PdfFontFactory.CreateFont(FontProgramFactory.CreateFont(StandardFonts.HELVETICA)); Paragraph paragraph = new Paragraph("This watermark is added UNDER the existing content") .SetFont(font) .SetFontSize(15); Canvas canvasWatermark1 = new Canvas(under, pdfDoc.GetDefaultPageSize()) .ShowTextAligned(paragraph, 297, 550, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0); canvasWatermark1.Close(); PdfCanvas over = new PdfCanvas(pdfDoc.GetFirstPage()); over.SetFillColor(ColorConstants.BLACK); paragraph = new Paragraph("This watermark is added ON TOP OF the existing content") .SetFont(font) .SetFontSize(15); Canvas canvasWatermark2 = new Canvas(over, pdfDoc.GetDefaultPageSize()) .ShowTextAligned(paragraph, 297, 500, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0); canvasWatermark2.Close(); paragraph = new Paragraph("This TRANSPARENT watermark is added ON TOP OF the existing content") .SetFont(font) .SetFontSize(15); over.SaveState(); // Creating a dictionary that maps resource names to graphics state parameter dictionaries PdfExtGState gs1 = new PdfExtGState(); gs1.SetFillOpacity(0.5f); over.SetExtGState(gs1); Canvas canvasWatermark3 = new Canvas(over, pdfDoc.GetDefaultPageSize()) .ShowTextAligned(paragraph, 297, 450, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0); canvasWatermark3.Close(); over.RestoreState(); pdfDoc.Close(); }
public virtual void TestSelectingCorrectAttachmentAlternative() { // TODO on completion of DEVSIX-3732 this test will probably have to be refactored // since we will have to emulate previous substitutions and populate the substitution info // to the glyph line so that mark is attached to the correct component of a ligature TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoNaskhArabic-Regular.ttf" ); GlyphLine glyphLine = new GlyphLine(JavaUtil.ArraysAsList(fontProgram.GetGlyphByCode(513), fontProgram.GetGlyphByCode (75))); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType5 lookup = (GposLookupType5)gposTableReader.GetLookupTable(3); glyphLine.idx = 1; lookup.TransformOne(glyphLine); NUnit.Framework.Assert.AreEqual(2, glyphLine.Size()); NUnit.Framework.Assert.AreEqual(513, glyphLine.Get(0).GetCode()); NUnit.Framework.Assert.AreEqual(75, glyphLine.Get(1).GetCode()); NUnit.Framework.Assert.AreEqual(-1, glyphLine.Get(1).GetAnchorDelta()); NUnit.Framework.Assert.AreEqual(-22, glyphLine.Get(1).GetXPlacement()); }
public static void generatePDF() { // Base URI is required to resolve the path to source files ConverterProperties converterProperties = new ConverterProperties(); using (var htmlStream = File.OpenRead(SRC)) { if (File.Exists(DEST)) { File.Delete(DEST); } using (var pdfStream = File.OpenWrite(DEST)) { FontProvider fontProvider = new DefaultFontProvider(); FontProgram fontProgram = FontProgramFactory.CreateFont(FONT); fontProvider.AddFont(fontProgram); converterProperties.SetFontProvider(fontProvider); HtmlConverter.ConvertToPdf(htmlStream, pdfStream, converterProperties); } } }
public virtual void VerifyDifferentXAdvanceIsAppliedSubFormat2() { TrueTypeFont fontProgram = (TrueTypeFont)FontProgramFactory.CreateFont(RESOURCE_FOLDER + "NotoSansMyanmar-Regular.ttf" ); GlyphPositioningTableReader gposTableReader = fontProgram.GetGposTable(); GposLookupType1 lookup = (GposLookupType1)gposTableReader.GetLookupTable(16); IList <Glyph> glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(401)), new Glyph(fontProgram .GetGlyphByCode(5))); GlyphLine gl = new GlyphLine(glyphs); NUnit.Framework.Assert.AreEqual(0, gl.Get(0).GetXAdvance()); NUnit.Framework.Assert.IsTrue(lookup.TransformOne(gl)); NUnit.Framework.Assert.AreEqual(109, gl.Get(0).GetXAdvance()); // Subtable type 2 defines different GposValueRecords for different coverage glyphs glyphs = JavaUtil.ArraysAsList(new Glyph(fontProgram.GetGlyphByCode(508)), new Glyph(fontProgram.GetGlyphByCode (5))); gl = new GlyphLine(glyphs); NUnit.Framework.Assert.AreEqual(0, gl.Get(0).GetXAdvance()); NUnit.Framework.Assert.IsTrue(lookup.TransformOne(gl)); NUnit.Framework.Assert.AreEqual(158, gl.Get(0).GetXAdvance()); }
public void ProcessRequest(HttpContext context) { string[] FONTS = { // msjh.ttc[0], the first one ttf in msjh.ttc. @"C:\Windows\Fonts\msjh.ttc,0", }; // If the POST body has uncoded symbols,such as "<" and ">", // it will be judged as potentially dangerous. And put the POST // body to Request.Unvalidated.Form. String HTML = context.Request.Unvalidated.Form["content"] == null ? context.Request.Form["content"]: context.Request.Unvalidated.Form["content"]; // Check whether the HTML has content. if (HTML != null && HTML != "") { // Define the date as the pdf file name. String strDate = DateTime.Now.ToString("yyyyMMddHHmmss"); String filename = "D:\\" + strDate + ".pdf"; ConverterProperties properties = new ConverterProperties(); // Deal with font provider. FontProvider fontProvider = new DefaultFontProvider(false, false, false); foreach (string font in FONTS) { FontProgram fontProgram = FontProgramFactory.CreateFont(font); fontProvider.AddFont(fontProgram); } // Set font type properties.SetFontProvider(fontProvider); // Set the base uri (that is, the root) of the website. // HttpContext.Current.Server.MapPath("~") : the root of website. properties.SetBaseUri(HttpContext.Current.Server.MapPath("~")); // Convert html to pdf. HtmlConverter.ConvertToPdf(WebUtility.HtmlDecode(HTML), new FileStream(filename, FileMode.Create), properties); Download(filename, strDate + ".pdf"); } }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); Document doc = new Document(pdfDoc); PdfFont font = PdfFontFactory.CreateFont(FontProgramFactory.CreateFont(StandardFonts.HELVETICA)); Paragraph paragraph = new Paragraph("My watermark (text)").SetFont(font).SetFontSize(30); ImageData img = ImageDataFactory.Create(IMG); float w = img.GetWidth(); float h = img.GetHeight(); PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.5f); // Implement transformation matrix usage in order to scale image for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) { PdfPage pdfPage = pdfDoc.GetPage(i); Rectangle pageSize = pdfPage.GetPageSize(); float x = (pageSize.GetLeft() + pageSize.GetRight()) / 2; float y = (pageSize.GetTop() + pageSize.GetBottom()) / 2; PdfCanvas over = new PdfCanvas(pdfPage); over.SaveState(); over.SetExtGState(gs1); if (i % 2 == 1) { doc.ShowTextAligned(paragraph, x, y, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0); } else { over.AddImageWithTransformationMatrix(img, w, 0, 0, h, x - (w / 2), y - (h / 2), true); } over.RestoreState(); } doc.Close(); }
public void HandleEvent(Event @event) { PdfDocumentEvent docEvent = (PdfDocumentEvent)@event; PdfDocument pdf = docEvent.GetDocument(); PdfPage page = docEvent.GetPage(); PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdf); pdfCanvas.AddXObject(stationery, 0, 0); if (mark != null && mark.Trim() != "") { //Rectangle rect = new Rectangle(36, 400, 36, 64); PdfFont font = PdfFontFactory.CreateFont(FontProgramFactory.CreateFont(StandardFonts.HELVETICA)); Paragraph p = new Paragraph(mark).SetFont(font).SetFontSize(100); pdfCanvas.SaveState(); PdfExtGState gs1 = new PdfExtGState(); gs1.SetFillOpacity(0.5f); pdfCanvas.SetExtGState(gs1); Canvas canvas = new Canvas(pdfCanvas, pdf, pdf.GetDefaultPageSize()) .ShowTextAligned(p, 297, 450, 1, TextAlignment.CENTER, VerticalAlignment.TOP, 0.785398F); pdfCanvas.RestoreState(); canvas.Close(); } }
/// <exception cref="System.IO.IOException"/> public static PdfFont CreateTtcFont(byte[] ttc, int ttcIndex, String encoding, bool embedded, bool cached) { FontProgram fontProgram = FontProgramFactory.CreateFont(ttc, ttcIndex, cached); return(CreateFont(fontProgram, encoding, embedded)); }
public TestSimpleFont(FontEncoding fontEncoding) { this.fontEncoding = fontEncoding; SetFontProgram(FontProgramFactory.CreateFont(StandardFonts.HELVETICA)); }
internal PdfType0Font(PdfDictionary fontDictionary) : base(fontDictionary) { newFont = false; PdfDictionary cidFont = fontDictionary.GetAsArray(PdfName.DescendantFonts).GetAsDictionary(0); PdfObject cmap = fontDictionary.Get(PdfName.Encoding); PdfObject toUnicode = fontDictionary.Get(PdfName.ToUnicode); CMapToUnicode toUnicodeCMap = FontUtil.ProcessToUnicode(toUnicode); if (cmap.IsName() && (PdfEncodings.IDENTITY_H.Equals(((PdfName)cmap).GetValue()) || PdfEncodings.IDENTITY_V .Equals(((PdfName)cmap).GetValue()))) { if (toUnicodeCMap == null) { String uniMap = GetUniMapFromOrdering(GetOrdering(cidFont)); toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(uniMap); if (toUnicodeCMap == null) { toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(PdfEncodings.IDENTITY_H); ILog logger = LogManager.GetLogger(typeof(iText.Kernel.Font.PdfType0Font)); logger.Error(MessageFormatUtil.Format(iText.IO.LogMessageConstant.UNKNOWN_CMAP, uniMap)); } } fontProgram = DocTrueTypeFont.CreateFontProgram(cidFont, toUnicodeCMap); cmapEncoding = CreateCMap(cmap, null); System.Diagnostics.Debug.Assert(fontProgram is IDocFontProgram); embedded = ((IDocFontProgram)fontProgram).GetFontFile() != null; } else { String cidFontName = cidFont.GetAsName(PdfName.BaseFont).GetValue(); String uniMap = GetUniMapFromOrdering(GetOrdering(cidFont)); if (uniMap != null && uniMap.StartsWith("Uni") && CidFontProperties.IsCidFont(cidFontName, uniMap)) { try { fontProgram = FontProgramFactory.CreateFont(cidFontName); cmapEncoding = CreateCMap(cmap, uniMap); embedded = false; } catch (System.IO.IOException) { fontProgram = null; cmapEncoding = null; } } else { if (toUnicodeCMap == null) { toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(uniMap); } if (toUnicodeCMap != null) { fontProgram = DocTrueTypeFont.CreateFontProgram(cidFont, toUnicodeCMap); cmapEncoding = CreateCMap(cmap, uniMap); } } if (fontProgram == null) { throw new PdfException(MessageFormatUtil.Format(PdfException.CannotRecogniseDocumentFontWithEncoding, cidFontName , cmap)); } } // DescendantFonts is a one-element array specifying the CIDFont dictionary that is the descendant of this Type 0 font. PdfDictionary cidFontDictionary = fontDictionary.GetAsArray(PdfName.DescendantFonts).GetAsDictionary(0); // Required according to the spec PdfName subtype = cidFontDictionary.GetAsName(PdfName.Subtype); if (PdfName.CIDFontType0.Equals(subtype)) { cidFontType = CID_FONT_TYPE_0; } else { if (PdfName.CIDFontType2.Equals(subtype)) { cidFontType = CID_FONT_TYPE_2; } else { LogManager.GetLogger(GetType()).Error(iText.IO.LogMessageConstant.FAILED_TO_DETERMINE_CID_FONT_SUBTYPE); } } longTag = new SortedSet <int>(); subset = false; }
internal PdfType0Font(PdfDictionary fontDictionary) : base(fontDictionary) { CheckFontDictionary(fontDictionary, PdfName.Type0); newFont = false; PdfDictionary cidFont = fontDictionary.GetAsArray(PdfName.DescendantFonts).GetAsDictionary(0); String cmap = fontDictionary.GetAsName(PdfName.Encoding).GetValue(); if (PdfEncodings.IDENTITY_H.Equals(cmap) || PdfEncodings.IDENTITY_V.Equals(cmap)) { PdfObject toUnicode = fontDictionary.Get(PdfName.ToUnicode); CMapToUnicode toUnicodeCMap = FontUtil.ProcessToUnicode(toUnicode); if (toUnicodeCMap == null) { String uniMap = GetUniMapFromOrdering(GetOrdering(cidFont)); toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(uniMap); if (toUnicodeCMap == null) { toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(PdfEncodings.IDENTITY_H); ILogger logger = LoggerFactory.GetLogger(typeof(iText.Kernel.Font.PdfType0Font)); logger.Error(String.Format(LogMessageConstant.UNKNOWN_CMAP, uniMap)); } } fontProgram = DocTrueTypeFont.CreateFontProgram(cidFont, toUnicodeCMap); cmapEncoding = new CMapEncoding(cmap); System.Diagnostics.Debug.Assert(fontProgram is IDocFontProgram); embedded = ((IDocFontProgram)fontProgram).GetFontFile() != null; cidFontType = CID_FONT_TYPE_2; } else { String cidFontName = cidFont.GetAsName(PdfName.BaseFont).GetValue(); String uniMap = GetUniMapFromOrdering(GetOrdering(cidFont)); if (uniMap != null && uniMap.StartsWith("Uni") && CidFontProperties.IsCidFont(cidFontName, uniMap)) { try { fontProgram = FontProgramFactory.CreateFont(cidFontName); cmapEncoding = new CMapEncoding(cmap, uniMap); embedded = false; } catch (System.IO.IOException) { fontProgram = null; cmapEncoding = null; } } else { CMapToUnicode toUnicodeCMap = FontUtil.GetToUnicodeFromUniMap(uniMap); if (toUnicodeCMap != null) { fontProgram = DocTrueTypeFont.CreateFontProgram(cidFont, toUnicodeCMap); cmapEncoding = new CMapEncoding(cmap, uniMap); } } if (fontProgram == null) { throw new PdfException(String.Format("Cannot recognise document font {0} with {1} encoding", cidFontName, cmap)); } cidFontType = CID_FONT_TYPE_0; } longTag = new LinkedDictionary <int, int[]>(); subset = false; }
public Task <byte[]> ManipulatePdf( StampSimple fileSource) { using MemoryStream pdfDest = new(); using MemoryStream pdfStream = new(fileSource.ImageSource); var pdfDoc = new PdfDocument(new PdfReader(pdfStream), new PdfWriter(pdfDest)); var doc = new Document(pdfDoc); foreach (TextProperties text in fileSource.Texts) { var font = PdfFontFactory.CreateFont(FontProgramFactory.CreateFont(text.FontName)); iText.Kernel.Colors.Color fontColor = iText.Kernel.Colors.ColorConstants.CYAN; switch (text.Color) { case "WHITE": fontColor = iText.Kernel.Colors.ColorConstants.WHITE; break; case "BLACK": fontColor = iText.Kernel.Colors.ColorConstants.BLACK; break; case "BLUE": fontColor = iText.Kernel.Colors.ColorConstants.BLUE; break; case "DARKGRAY": fontColor = iText.Kernel.Colors.ColorConstants.DARK_GRAY; break; case "GRAY": fontColor = iText.Kernel.Colors.ColorConstants.GRAY; break; case "GREEN": fontColor = iText.Kernel.Colors.ColorConstants.GREEN; break; case "MAGENTA": fontColor = iText.Kernel.Colors.ColorConstants.MAGENTA; break; case "ORANGE": fontColor = iText.Kernel.Colors.ColorConstants.ORANGE; break; case "PINK": fontColor = iText.Kernel.Colors.ColorConstants.PINK; break; case "RED": fontColor = iText.Kernel.Colors.ColorConstants.RED; break; case "YELLOW": fontColor = iText.Kernel.Colors.ColorConstants.YELLOW; break; } var paragraph = new Paragraph(text.Text).SetFont(font).SetFontSize(text.FontSize).SetFontColor(fontColor); var gs1 = new PdfExtGState().SetFillOpacity(text.Opacity); for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++) { PdfPage pdfPage = pdfDoc.GetPage(i); Rectangle pageSize = pdfPage.GetPageSize(); float x = (pageSize.GetLeft() + pageSize.GetRight()) / 2; float y = (pageSize.GetTop() + pageSize.GetBottom()) / 2; var over = new PdfCanvas(pdfPage); over.SaveState(); over.SetExtGState(gs1); doc.ShowTextAligned(paragraph, text.PosX, text.PosY, i, TextAlignment.CENTER, VerticalAlignment.TOP, text.Radio); over.RestoreState(); } } doc.Close(); return(Task.FromResult(pdfDest.ToArray())); }
/// <exception cref="System.IO.IOException"/> public static PdfFont CreateFont(String path, String encoding, bool embedded, bool cached) { FontProgram fontProgram = FontProgramFactory.CreateFont(path, cached); return(CreateFont(fontProgram, encoding, embedded)); }
public static void Main(string[] args) { // string path = @"C:\Users\Intern03.ELIKOSOFT\Desktop\MyProjects\IText7\TextExamples\demo.pdf"; // string dirPath =@"C:\Users\Intern03.ELIKOSOFT\Desktop\MyProjects\IText7\TextExamples"; // // // // if(File.Exists(path)) // File.Delete(path); // // // var directory= Directory.GetFiles(dirPath); // foreach (var file in directory) // { // File.Delete(file); // } // Must have write permissions to the path folder PdfWriter writer = new PdfWriter(@"C:\Users\Intern03.ELIKOSOFT\Desktop\MyProjects\IText7\TextExamples\demo.pdf"); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf, PageSize.A4, true); //var font = PdfFontFactory.CreateFont(FontConstants.TIMES_ROMAN); #region Creating Cyrillic Font //the path to the physical font file TTF on the drive string fontPath = $@"C:\Users\Intern03.ELIKOSOFT\Desktop\MyProjects\IText7\TextExamples\MAC_C_Times\MCTIME.TTF"; FontProgram fontProgram = FontProgramFactory.CreateFont(fontPath); PdfFont font = PdfFontFactory.CreateFont( fontProgram, PdfEncodings.WINANSI, true); #endregion // var header = new Paragraph("Edine~ni Merki").SetTextAlignment(TextAlignment.CENTER) // .SetFontSize(20).SetFont(font); var header = new Paragraph("Magacini").SetTextAlignment(TextAlignment.CENTER) .SetFontSize(20).SetFont(font); Image img = new Image(ImageDataFactory .Create(@"C:\Users\Intern03.ELIKOSOFT\Desktop\MyProjects\IText7\logo.jpg")) .SetTextAlignment(TextAlignment.CENTER); img.Scale(4, 4); document.Add(img); document.Add(header); // Table Table table = new Table(2, false); table.SetWidth(400).SetHorizontalAlignment(HorizontalAlignment.CENTER); Cell cell11 = new Cell(1, 1) .SetBackgroundColor(ColorConstants.GRAY) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("Broj na magacin")).SetFont(font); Cell cell12 = new Cell(1, 1) .SetBackgroundColor(ColorConstants.GRAY) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("Naziv na magacin")).SetFont(font); ////Uncomment for Measure Units Example // Cell cell11 = new Cell(1, 1) // .SetBackgroundColor(ColorConstants.YELLOW) // .SetTextAlignment(TextAlignment.CENTER) // .Add(new Paragraph("Edine~na merka")).SetFont(font); // Cell cell12 = new Cell(1, 1) // .SetBackgroundColor(ColorConstants.YELLOW) // .SetTextAlignment(TextAlignment.CENTER) // .Add(new Paragraph("Naziv na edine~na merka")).SetFont(font); Cell cell21 = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("New York")); Cell cell22 = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("Albany")); Cell cell31 = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("New Jersey")); Cell cell32 = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("Trenton")); Cell cell41 = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("California")); Cell cell42 = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph("Sacramento")); table.AddCell(cell11); table.AddCell(cell12); ////Uncomment for Measure Units Example // foreach (KeyValuePair<string, string> item in Entities.SampleCollection) // { // Cell cellKey = new Cell(1, 1) // .SetTextAlignment(TextAlignment.CENTER) // .Add(new Paragraph(item.Key)).SetFont(font); // // Cell cellValue = new Cell(1, 1) // .SetTextAlignment(TextAlignment.CENTER) // .Add(new Paragraph(item.Value)).SetFont(font); // // table.AddCell(cellKey); // table.AddCell(cellValue); // } foreach (KeyValuePair <string, string> item in Entities.ReadyWarehouses()) { Cell cellKey = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph(item.Key)).SetFont(font); Cell cellValue = new Cell(1, 1) .SetTextAlignment(TextAlignment.CENTER) .Add(new Paragraph(item.Value)).SetFont(font); table.AddCell(cellKey); table.AddCell(cellValue); } // for (int i = 0; i < Coll.words.Count(); i++) // { // Cell cell = new Cell(1, 1) // .SetTextAlignment(TextAlignment.CENTER) // .Add(new Paragraph(Coll.words.ElementAt(i))); // // table.AddCell(cell); // } document.Add(table); document.Close(); }
internal static Type1Font CreateFontProgram(PdfDictionary fontDictionary, FontEncoding fontEncoding, CMapToUnicode toUnicode) { PdfName baseFontName = fontDictionary.GetAsName(PdfName.BaseFont); String baseFont; if (baseFontName != null) { baseFont = baseFontName.GetValue(); } else { baseFont = FontUtil.CreateRandomFontName(); } if (!fontDictionary.ContainsKey(PdfName.FontDescriptor)) { Type1Font type1StdFont; try { //if there are no font modifiers, cached font could be used, //otherwise a new instance should be created. type1StdFont = (Type1Font)FontProgramFactory.CreateFont(baseFont, true); } catch (Exception) { type1StdFont = null; } if (type1StdFont != null) { return(type1StdFont); } } iText.Kernel.Font.DocType1Font fontProgram = new iText.Kernel.Font.DocType1Font(baseFont); PdfDictionary fontDesc = fontDictionary.GetAsDictionary(PdfName.FontDescriptor); fontProgram.subtype = fontDesc.GetAsName(PdfName.Subtype); FillFontDescriptor(fontProgram, fontDesc); PdfNumber firstCharNumber = fontDictionary.GetAsNumber(PdfName.FirstChar); int firstChar = firstCharNumber != null?Math.Max(firstCharNumber.IntValue(), 0) : 0; int[] widths = FontUtil.ConvertSimpleWidthsArray(fontDictionary.GetAsArray(PdfName.Widths), firstChar, fontProgram .GetMissingWidth()); fontProgram.avgWidth = 0; int glyphsWithWidths = 0; for (int i = 0; i < 256; i++) { Glyph glyph = new Glyph(i, widths[i], fontEncoding.GetUnicode(i)); fontProgram.codeToGlyph[i] = glyph; if (glyph.HasValidUnicode()) { //FontEncoding.codeToUnicode table has higher priority if (fontEncoding.ConvertToByte(glyph.GetUnicode()) == i) { fontProgram.unicodeToGlyph[glyph.GetUnicode()] = glyph; } } else { if (toUnicode != null) { glyph.SetChars(toUnicode.Lookup(i)); } } if (widths[i] > 0) { glyphsWithWidths++; fontProgram.avgWidth += widths[i]; } } if (glyphsWithWidths != 0) { fontProgram.avgWidth /= glyphsWithWidths; } return(fontProgram); }
/// <exception cref="System.IO.IOException"/> public static PdfFont CreateFont(byte[] font, String encoding, bool embedded, bool cached) { FontProgram fontProgram = FontProgramFactory.CreateFont(null, font, cached); return(CreateFont(fontProgram, encoding, embedded)); }
/// <summary>Returns the Font.</summary> /// <returns>the font</returns> /// <exception cref="System.IO.IOException"/> public virtual FontProgram GetFont() { if (font != null) { return(font); } FontProgram ff2 = FontProgramFactory.CreateRegisteredFont(faceName, ((italic != 0) ? FontConstants.ITALIC : 0) | ((bold != 0) ? FontConstants.BOLD : 0)); encoding = FontEncoding.CreateFontEncoding(PdfEncodings.WINANSI); font = ff2; if (font != null) { return(font); } String fontName; if (faceName.Contains("courier") || faceName.Contains("terminal") || faceName.Contains("fixedsys")) { fontName = fontNames[MARKER_COURIER + italic + bold]; } else { if (faceName.Contains("ms sans serif") || faceName.Contains("arial") || faceName.Contains("system")) { fontName = fontNames[MARKER_HELVETICA + italic + bold]; } else { if (faceName.Contains("arial black")) { fontName = fontNames[MARKER_HELVETICA + italic + MARKER_BOLD]; } else { if (faceName.Contains("times") || faceName.Contains("ms serif") || faceName.Contains("roman")) { fontName = fontNames[MARKER_TIMES + italic + bold]; } else { if (faceName.Contains("symbol")) { fontName = fontNames[MARKER_SYMBOL]; } else { int pitch = pitchAndFamily & 3; int family = (pitchAndFamily >> 4) & 7; switch (family) { case FF_MODERN: { fontName = fontNames[MARKER_COURIER + italic + bold]; break; } case FF_ROMAN: { fontName = fontNames[MARKER_TIMES + italic + bold]; break; } case FF_SWISS: case FF_SCRIPT: case FF_DECORATIVE: { fontName = fontNames[MARKER_HELVETICA + italic + bold]; break; } default: { switch (pitch) { case FIXED_PITCH: { fontName = fontNames[MARKER_COURIER + italic + bold]; break; } default: { fontName = fontNames[MARKER_HELVETICA + italic + bold]; break; } } break; } } } } } } } try { font = FontProgramFactory.CreateFont(fontName); encoding = FontEncoding.CreateFontEncoding(PdfEncodings.WINANSI); } catch (System.IO.IOException e) { throw new Exception(e.Message, e); } return(font); }