/// <summary>
        /// Attempts to retrieve the specified font from the System's Fonts folder
        /// and registers the font with WPF.
        /// </summary>
        /// <param name="fontName">Name of the font.</param>
        /// <returns></returns>
        private static PdfFont GetFont(string fontName)
        {
            if (!PdfFontFactory.IsRegistered(fontName))
            {
                var fontPath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\" + fontName.Replace(" ", "") + ".ttf";
                PdfFontFactory.Register(fontPath);
            }

            return(PdfFontFactory.CreateRegisteredFont(fontName));
        }
Beispiel #2
0
        public int GetAllignedFontSizeForMultiLines <T>(T detail, int defaultFontSize = 9)
        {
            IDictionary <String, PdfFormField> fields = _form.GetFormFields();

            Type type = detail.GetType();

            PropertyInfo[] properties     = type.GetProperties();
            int            targetFontsize = 0;

            foreach (PropertyInfo property in properties)
            {
                PdfFormField       toSet;
                PdfActionAttribute required = property.GetCustomAttribute <PdfActionAttribute>();

                if (fields.TryGetValue(property.Name, out toSet))
                {
                    var value = property.GetValue(detail, null);
                    if (!string.IsNullOrWhiteSpace(value?.ToString()))
                    {
                        if (required != null && required.Action.Equals(ActionFlag.MultiLines))
                        {
                            PdfFormField field    = fields[property.Name];
                            PdfArray     position = field.GetWidgets().First().GetRectangle();
                            float        width    = (float)(position.GetAsNumber(2).GetValue() - position.GetAsNumber(0).GetValue());
                            float        height   = (float)(position.GetAsNumber(3).GetValue() - position.GetAsNumber(1).GetValue());

                            PdfFontAttribute pdfFont = property.GetCustomAttribute <PdfFontAttribute>();
                            var font = pdfFont?.Type != null
                                ? PdfFontFactory.CreateRegisteredFont(pdfFont.Type)
                                : PdfFontFactory.CreateRegisteredFont(DefaultFont);

                            int latestTargetFontSize = GetFontSizeFittingMultiLinesInAcroForm(value.ToString(), width, height, font, defaultFontSize);
                            if (targetFontsize == 0)
                            {
                                targetFontsize = latestTargetFontSize;
                            }
                            else
                            {
                                targetFontsize = targetFontsize > latestTargetFontSize
                                    ? latestTargetFontSize
                                    : targetFontsize;
                            }
                        }
                    }
                }
            }
            return(targetFontsize);
        }
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document    doc    = new Document(pdfDoc);

            String fontName = "Greek-Regular";

            PdfFontFactory.Register(FONT, fontName);
            PdfFont f = PdfFontFactory.CreateRegisteredFont(fontName, PdfEncodings.CP1253, true);

            // "Νύφες"
            Paragraph p = new Paragraph("\u039d\u03cd\u03c6\u03b5\u03c2").SetFont(f);

            doc.Add(p);

            doc.Close();
        }
 /// <summary>
 /// 字体设置
 /// </summary>
 /// <typeparam name="TContent">内容类型</typeparam>
 /// <param name="font">字体定义</param>
 /// <param name="obj">对象</param>
 protected static void SetFont <TContent>(ContentFont font, ElementPropertyContainer <TContent> obj) where TContent : IPropertyContainer
 {
     if (font != null)
     {
         if (font.Style == null)
         {
             obj.SetFont(PdfFontFactory.CreateRegisteredFont(font.Name, PdfEncodings.IDENTITY_H, font.Embedded, true));
         }
         else
         {
             obj.SetFont(PdfFontFactory.CreateRegisteredFont(font.Name, PdfEncodings.IDENTITY_H, font.Embedded, font.Style.Value, true));
         }
         if (font.Size != null)
         {
             obj.SetFontSize(font.Size.Value);
         }
         if (font.Color != null)
         {
             obj.SetFontColor(font.Color);
         }
     }
 }
Beispiel #5
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);

            foreach (String font in FONTS)
            {
                PdfFontFactory.Register(font);
            }

            PdfFont defaultFont = doc.GetDefaultProperty<PdfFont>(Property.FONT);
            
            HashSet<String> fonts = new HashSet<String>(FontProgramFactory.GetRegisteredFonts());
            foreach (String fontname in fonts)
            {
                Console.WriteLine(fontname);
                PdfFont font;
                try
                {
                    font = PdfFontFactory.CreateRegisteredFont(fontname, PdfEncodings.IDENTITY_H);
                }
                catch (ArgumentException e)
                {
                    doc.Add(new Paragraph(String.Format("The font {0} doesn't have unicode support: {1}",
                        fontname, e.Message)));
                    continue;
                }

                doc.Add(new Paragraph(String.Format("Postscript name for {0}: {1}", fontname,
                    font.GetFontProgram().GetFontNames().GetFontName())));
                doc.SetFont(font);
                ShowFontInfo(doc);
                
                // Restore the default document font
                doc.SetFont(defaultFont);
            }

            doc.Close();
        }
Beispiel #6
0
        public void FillMultiLinesInAcroForm <T>(T detail, int fontSize)
        {
            IDictionary <String, PdfFormField> fields = _form.GetFormFields();

            Type type = detail.GetType();

            PropertyInfo[] properties = type.GetProperties();

            foreach (PropertyInfo property in properties)
            {
                PdfFormField       toSet;
                PdfActionAttribute required = property.GetCustomAttribute <PdfActionAttribute>();

                if (fields.TryGetValue(property.Name, out toSet))
                {
                    var value = property.GetValue(detail, null);
                    if (!string.IsNullOrWhiteSpace(value?.ToString()))
                    {
                        if (required != null && required.Action.Equals(ActionFlag.MultiLines))
                        {
                            PdfFontAttribute pdfFont = property.GetCustomAttribute <PdfFontAttribute>();
                            var font = pdfFont?.Type != null
                                ? PdfFontFactory.CreateRegisteredFont(pdfFont.Type)
                                : PdfFontFactory.CreateRegisteredFont(DefaultFont);

                            toSet.SetValue(value.ToString()).SetFontAndSize(font, fontSize);

                            if (pdfFont != null)
                            {
                                toSet.SetColor(pdfFont.Color);
                            }
                        }
                    }
                }
            }
        }
Beispiel #7
0
        public virtual void HandleEvent(Event pdfEvent)
        {
            {
                PdfDocumentEvent docEvent = (PdfDocumentEvent)pdfEvent;
                PdfDocument      pdfDoc   = docEvent.GetDocument();
                Document         document = new Document(pdfDoc);
                PdfPage          page     = docEvent.GetPage();
                int       pageNumber      = pdfDoc.GetPageNumber(page);
                Rectangle pageSize        = page.GetPageSize();

                PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);

                //Add header and footer
                PdfFont font = PdfFontFactory.CreateRegisteredFont("calibri-bold");

                if (pageNumber == 1)
                {
                    if (_docOptions.HasFlag(DocConverter.DocOptions.AddHeaderPageOne))
                    {
                        pdfCanvas.SaveState();
                        PdfExtGState state = new PdfExtGState();
                        state.SetFillOpacity(1.0f);
                        pdfCanvas.SetExtGState(state);

                        var imageHeight = _idHeaderFirst.GetHeight() * 72 / 96; //convert pixels to points
                        var imageToAdd  = new Image(_idHeaderFirst, 0, pageSize.GetTop() - imageHeight, pageSize.GetWidth());

                        imageToAdd.GetAccessibilityProperties()
                        .SetAlternateDescription("Background header image");
                        imageToAdd.GetAccessibilityProperties().SetRole(StandardRoles.ARTIFACT);

                        PdfLayer pdflayer = new PdfLayer("main layer", pdfDoc);

                        pdflayer.SetOn(true);
                        Canvas canvas = new Canvas(pdfCanvas, pdfDoc,
                                                   document.GetPageEffectiveArea(pdfDoc.GetDefaultPageSize()));
                        pdflayer.SetPageElement("L");
                        pdfCanvas.BeginLayer(pdflayer);
                        canvas.EnableAutoTagging(page);
                        canvas.Add(imageToAdd);
                        pdfCanvas.EndLayer();
                    }

                    if (_docOptions.HasFlag(DocConverter.DocOptions.DisplayTitle))
                    {
                        //Add Title
                        Color          purpleColor = new DeviceRgb(85, 60, 116);
                        TagTreePointer tagPointer  = new TagTreePointer(pdfDoc);
                        tagPointer.SetPageForTagging(page);
                        tagPointer.AddTag(StandardRoles.TITLE);
                        pdfCanvas.BeginText().SetColor(purpleColor, true).SetFontAndSize(font, 28)
                        .MoveText(42, pageSize.GetTop() - 150).OpenTag(tagPointer.GetTagReference()).ShowText(_title).CloseTag().Stroke();
                    }
                }
                else if (_docOptions.HasFlag(DocConverter.DocOptions.AddHeaderAllPages))
                {
                    pdfCanvas.SaveState();
                    PdfExtGState state = new PdfExtGState();
                    state.SetFillOpacity(1.0f);
                    pdfCanvas.SetExtGState(state);
                    var imageHeight = _idHeaderAll.GetHeight() * 72 / 96; //convert pixels to points
                    var imageToAdd  = new Image(_idHeaderAll, 0, pageSize.GetTop() - imageHeight, pageSize.GetWidth());
                    imageToAdd.GetAccessibilityProperties().SetRole(StandardRoles.ARTIFACT);
                    imageToAdd.GetAccessibilityProperties()
                    .SetAlternateDescription("Background header image");
                    PdfLayer pdflayer = new PdfLayer("main layer", pdfDoc);

                    pdflayer.SetOn(true);

                    Canvas canvas = new Canvas(pdfCanvas, pdfDoc,
                                               document.GetPageEffectiveArea(pdfDoc.GetDefaultPageSize()));

                    pdfCanvas.BeginLayer(pdflayer);
                    canvas.EnableAutoTagging(page);
                    canvas.Add(imageToAdd);
                    pdfCanvas.EndLayer();
                    pdfCanvas.RestoreState();
                }

                if (_docOptions.HasFlag(DocConverter.DocOptions.AddLineBottomEachPage))
                {
                    //Add line to the bottom
                    Color blueColor = new DeviceCmyk(100, 25, 0, 39);

                    pdfCanvas.SetStrokeColor(blueColor)
                    .MoveTo(36, 36)
                    .LineTo(559, 36)
                    .ClosePathStroke();
                }


                pdfCanvas.Release();
            }
        }
 /// <summary>
 /// 创建字体
 /// </summary>
 /// <param name="fontName">字体名</param>
 /// <param name="size">字号</param>
 /// <returns>返回创建成功的字体对象</returns>
 protected PdfFont CreateFont(string fontName, float size)
 {
     return(PdfFontFactory.CreateRegisteredFont(fontName, PdfEncodings.IDENTITY_H, false));
 }
        /// <summary>
        /// 创建字体
        /// </summary>
        /// <param name="fontName">字体名</param>
        /// <param name="size">字号</param>
        /// <param name="style">样式</param>
        /// <param name="color">颜色</param>
        /// <returns>返回创建成功的字体对象</returns>
        protected PdfFont CreateFont(string fontName, float size, int style, Color color)
        {
            var font = PdfFontFactory.CreateRegisteredFont(fontName, PdfEncodings.IDENTITY_H, false, style);

            return(font);
        }
        //static private ResumeData data;
        public DocumentBuilder()//ResumeData import)
        {
            //data = import;

            String    docname = "Test";
            PdfWriter writer  = null;
            bool      read    = false;

            try  // Try writing to file
            {
                writer = new PdfWriter(docname + ".pdf");
                read   = true;
            }
            catch  // Catch if file is open and display message to user
            {
                string            message = "Please close the open PDF or save using a different name.";
                string            caption = "Active PDF Open in Another Window";
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult      msg;
                msg = MessageBox.Show(message, caption, buttons);
                Console.WriteLine("Please close the pdf file that is open");
            }
            if (read)
            {
                PdfDocument pdf = new PdfDocument(writer);
                Document    doc = new Document(pdf);

                /* Import Data */
                JSONHandler jhandle = new JSONHandler();
                ResumeData  data    = jhandle.ReadFromJSON();


                /*---------------------------           Writing to doc            ------------------------------------*/



                /* Register Fonts */
                PdfFontFactory.RegisterDirectory("C:\\Windows\\Fonts");
                PdfFont Courier = PdfFontFactory.CreateRegisteredFont("Courier New");
                PdfFont Gothic  = PdfFontFactory.CreateRegisteredFont("Century Gothic");

                /* Create Content */
                Paragraph Name = new Paragraph(data.Name)
                                 .SetTextAlignment(TextAlignment.CENTER)
                                 .SetFont(Courier)
                                 .SetFontSize(34);

                Paragraph Bio = new Paragraph(data.Email + " | " + data.Phone + " | " + data.Address1)
                                .SetTextAlignment(TextAlignment.CENTER)
                                .SetFont(Gothic)
                                .SetFontSize(9);

                Paragraph Site = new Paragraph()
                                 .Add(new Link("Barnes7619.com", PdfAction.CreateURI("https://Barnes7619.com")).SetUnderline())
                                 .SetTextAlignment(TextAlignment.CENTER)
                                 .SetFont(Gothic)
                                 .SetFontSize(9);


                Table SummaryHead = CreateSeparator("Summary", Courier);

                Table EducationHead = CreateSeparator("Education & Training", Courier);

                Table SoftwareHead = CreateSeparator("Software Experience", Courier);

                Table ExperienceHead = CreateSeparator("Experience", Courier);

                Table SkillsHead = CreateSeparator("Skills", Courier);



                ///* Formatting */
                //Name.Alignment = Element.ALIGN_CENTER;
                //Bio.Alignment = Element.ALIGN_CENTER;
                //Site.Alignment = Element.ALIGN_CENTER;

                /* Add Content to Document */
                doc.Add(Name);
                doc.Add(Bio);
                doc.Add(Site);
                doc.Add(SummaryHead);
                doc.Add(EducationHead);
                doc.Add(SoftwareHead);
                doc.Add(ExperienceHead);
                doc.Add(SkillsHead);

                /* Close Document */
                doc.Close();



                /* -------------------------  Completed Message  --------------------------- */
                string            message = "Resume Generated!";
                string            caption = "Finished";
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult      msg;
                msg = MessageBox.Show(message, caption, buttons);
            }
        }
Beispiel #11
0
        public void FillTextInAcroForm <T>(T detail)
        {
            IDictionary <String, PdfFormField> fields = _form.GetFormFields();

            Type type = detail.GetType();

            PropertyInfo[] properties  = type.GetProperties();
            PdfFont        defaultFont = PdfFontFactory.CreateRegisteredFont(DefaultFont);

            foreach (PropertyInfo property in properties)
            {
                PdfFormField       toSet;
                PdfActionAttribute required = property.GetCustomAttribute <PdfActionAttribute>();

                if (required != null &&
                    (required.Action.Equals(ActionFlag.Ignore) ||
                     required.Action.Equals(ActionFlag.MultiLines)))
                {
                    continue;
                }

                if (fields.TryGetValue(property.Name, out toSet))
                {
                    var value = property.GetValue(detail, null);
                    if (!string.IsNullOrWhiteSpace(value?.ToString()))
                    {
                        toSet.SetValue(value.ToString()).SetReadOnly(true);

                        PdfFontAttribute pdfFont = property.GetCustomAttribute <PdfFontAttribute>();
                        if (pdfFont != null)
                        {
                            var font = pdfFont.Type != null
                                ? PdfFontFactory.CreateRegisteredFont(pdfFont.Type)
                                : defaultFont;

                            if (pdfFont.IsAutoScaleToBlock)
                            {
                                PdfArray position = toSet.GetWidgets().First().GetRectangle();
                                float    width    = (float)(position.GetAsNumber(2).GetValue() - position.GetAsNumber(0).GetValue());
                                float    height   = (float)(position.GetAsNumber(3).GetValue() - position.GetAsNumber(1).GetValue());

                                pdfFont.Size =
                                    GetFontSizeFittingMultiLinesInAcroForm(value.ToString(), width, height, font, pdfFont.Size != 0 ? pdfFont.Size : 12);
                            }

                            // default justification for form is from top left

                            if (pdfFont.Justification == PdfTextAlignment.CenterLeft ||
                                pdfFont.Justification == PdfTextAlignment.CenterMiddle ||
                                pdfFont.Justification == PdfTextAlignment.CenterRight ||
                                pdfFont.Justification == PdfTextAlignment.BottomLeft ||
                                pdfFont.Justification == PdfTextAlignment.BottomMiddle ||
                                pdfFont.Justification == PdfTextAlignment.BottomRight)
                            {
                                VerticalJustificationInAcroForm(toSet, detail, property.Name, font, pdfFont);
                                continue;
                            }

                            if (pdfFont.Justification == PdfTextAlignment.TopLeft ||
                                pdfFont.Justification == PdfTextAlignment.TopMiddle ||
                                pdfFont.Justification == PdfTextAlignment.TopRight)
                            {
                                toSet.SetJustification((int)pdfFont.Justification);
                            }

                            toSet.SetFont(font);

                            if (pdfFont.Size == 0)
                            {
                                toSet.SetFontSizeAutoScale();
                            }
                            else
                            {
                                toSet.SetFontSize(pdfFont.Size);
                            }

                            toSet.SetColor(pdfFont.Color);

                            if (!string.IsNullOrWhiteSpace(pdfFont.WarningCondition))
                            {
                                if (pdfFont.IsWarning(value.ToString(), pdfFont.WarningCondition))
                                {
                                    toSet.SetColor(Color.RED);
                                }
                            }
                        }
                        else
                        {
                            toSet.SetValue(value.ToString()).SetFont(defaultFont).SetFontSizeAutoScale().SetReadOnly(true);
                        }
                    }
                    else
                    {
                        if (required != null)
                        {
                            if (required.Action.Equals(ActionFlag.Required))
                            {
                                throw new ArgumentException($"{property.Name} is missing");
                            }
                            if (required.Action.Equals(ActionFlag.Optional))
                            {
                                continue;
                            }
                            if (required.Action.Equals(ActionFlag.NotAvailable))
                            {
                                toSet.SetValue("N/A").SetFontSizeAutoScale().SetReadOnly(true);
                            }
                        }
                    }
                }
            }
        }
Beispiel #12
0
        public Task WriteAnnotatedPdfAsync(string pdfDocumentPath, IEnumerable <IAnnotation> annotations, string filePath)
        {
            using (var reader = new PdfReader(pdfDocumentPath))
                using (var outFile = File.Open(filePath, FileMode.Create))
                    using (var writer = new PdfWriter(outFile))
                        using (var doc = new PdfDocument(reader, writer))
                        {
                            var acroForm = PdfAcroForm.GetAcroForm(doc, true);
                            foreach (var ann in annotations)
                            {
                                var targets = ann.SelectedTargets;
                                if (targets == null || targets.Count < 1)
                                {
                                    targets = ann.Subject.Appearances ?? throw new ArgumentException($"The subject word {ann.Subject.Text} for a given annotation has no appearances.");
                                }
                                foreach (var trg in targets)
                                {
                                    var page = doc.GetPage(trg.Parent.Index + 1);

                                    var font       = PdfFontFactory.CreateRegisteredFont(iText.IO.Font.Constants.StandardFonts.HELVETICA);
                                    var coord      = trg.GetPdfCoords();
                                    var buttonRect = new Rectangle(coord.Llx, coord.Lly, coord.width, coord.height);
                                    var txRect     = GetAnnotationRect(buttonRect, font, ann, trg);

                                    var textFieldName = Guid.NewGuid().ToString("n");
                                    var textField     = PdfFormField.CreateText(doc, txRect, textFieldName);
                                    textField.SetValue(ann.Content, font, FontSize);
                                    textField.SetColor(ColorConstants.DARK_GRAY);
                                    textField.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
                                    textField.SetReadOnly(true);
                                    textField.SetMultiline(true);
                                    textField.SetVisibility(PdfFormField.HIDDEN);
                                    textField.SetBorderColor(ColorConstants.LIGHT_GRAY);
                                    textField.SetFieldFlags(4097);

                                    acroForm.AddField(textField, page);

                                    var enter = PdfAction.CreateHide(textFieldName, false);
                                    var exit  = PdfAction.CreateHide(textFieldName, true);

                                    var btn = PdfFormField.CreatePushButton(doc, buttonRect, Guid.NewGuid().ToString("n"),
                                                                            string.Empty);
                                    btn.SetBackgroundColor(null);
                                    btn.SetBorderWidth(0);
                                    btn.SetAdditionalAction(PdfName.E, enter);
                                    btn.SetAdditionalAction(PdfName.X, exit);
                                    acroForm.AddField(btn, page);

                                    var underline = PdfTextMarkupAnnotation.CreateUnderline(new Rectangle(buttonRect.GetX(), buttonRect.GetY() - 2, buttonRect.GetWidth(), 3),
                                                                                            new float[]
                                    {
                                        buttonRect.GetX() + buttonRect.GetWidth(), buttonRect.GetY() + buttonRect.GetHeight(),
                                        buttonRect.GetX(), buttonRect.GetY() + buttonRect.GetHeight(),
                                        buttonRect.GetX() + buttonRect.GetWidth(), buttonRect.GetY() - 2,
                                        buttonRect.GetX(), buttonRect.GetY() - 2,
                                    });
                                    underline.SetColor(ColorConstants.YELLOW);
                                    page.AddAnnotation(underline);
                                }
                            }
                        }
            return(Task.CompletedTask);
        }