private PdfFormField MergeFieldsWithTheSameName(PdfFormField existingField, PdfFormField newField) { String fieldName = newField.GetFieldName().ToUnicodeString(); existingField.GetPdfObject().Remove(PdfName.T); PdfFormField mergedField = formTo.GetField(fieldName); PdfArray kids = mergedField.GetKids(); if (kids != null && !kids.IsEmpty()) { mergedField.AddKid(existingField); return(mergedField); } newField.GetPdfObject().Remove(PdfName.T); mergedField = PdfFormField.CreateEmptyField(documentTo); formTo.GetFields().Remove(newField.GetPdfObject()); mergedField.Put(PdfName.FT, existingField.GetFormType()).Put(PdfName.T, new PdfString(fieldName)); PdfDictionary parent = existingField.GetParent(); if (parent != null) { mergedField.Put(PdfName.Parent, parent); } kids = existingField.GetKids(); if (kids != null) { mergedField.Put(PdfName.Kids, kids); } mergedField.AddKid(existingField).AddKid(newField); return(mergedField); }
/** * @see com.lowagie.text.pdf.PdfPageEvent#onGenericTag(com.lowagie.text.pdf.PdfWriter, com.lowagie.text.Document, com.lowagie.text.Rectangle, java.lang.String) */ public override void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { rect.Bottom = rect.Bottom - 3; PdfFormField field = (PdfFormField)genericChunkFields[text]; if (field == null) { TextField tf = new TextField(writer, new Rectangle(rect.GetLeft(padding), rect.GetBottom(padding), rect.GetRight(padding), rect.GetTop(padding)), text); tf.FontSize = 14; field = tf.GetTextField(); } else { field.Put(PdfName.RECT, new PdfRectangle(rect.GetLeft(padding), rect.GetBottom(padding), rect.GetRight(padding), rect.GetTop(padding))); } if (parent == null) { writer.AddAnnotation(field); } else { parent.AddKid(field); } }
public virtual void RemoveKidTest() { // Creating input document String inputFile = "in_removeKidTest.pdf"; PdfDocument inDoc = new PdfDocument(new PdfWriter(destinationFolder + inputFile)); inDoc.AddNewPage(); PdfFormField root = PdfFormField.CreateEmptyField(inDoc); root.SetFieldName("root"); PdfFormField child = PdfFormField.CreateEmptyField(inDoc); child.SetFieldName("child"); root.AddKid(child); PdfAcroForm.GetAcroForm(inDoc, true).AddField(root); inDoc.Close(); // Creating stamping document String outputFile = "removeKidTest.pdf"; PdfReader reader = new PdfReader(destinationFolder + inputFile); PdfWriter writer = new PdfWriter(destinationFolder + outputFile); PdfDocument outputDoc = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode()); PdfAcroForm.GetAcroForm(outputDoc, true).RemoveField("root.child"); outputDoc.Close(); CompareWithCmp(outputFile); }
public float AddRadioGroup(ItemRef item, Rectangle rectStart, List <String> labels, int distance) { int fieldFlags = 0; float curY = rectStart.Top; drawingFuncs.Add(() => { PdfFormField group = PdfFormField.CreateRadioButton(writer, true); group.FieldName = item.UniqueId; for (int i = 0; i < labels.Count; i++) { Rectangle rect = new Rectangle(rectStart.Left + i * distance, rectStart.Top, rectStart.Right + i * distance, rectStart.Bottom); RadioCheckField tf = new RadioCheckField(Writer, rect, item.UniqueId + "_" + i.ToString(), i.ToString()) { BackgroundColor = new GrayColor(0.8f), BorderColor = GrayColor.BLACK, CheckType = RadioCheckField.TYPE_CIRCLE, BorderStyle = PdfBorderDictionary.STYLE_SOLID, FontSize = 12 }; group.AddKid(tf.RadioField); } if (item.IsMandatory) { fieldFlags = fieldFlags | PdfFormField.FF_REQUIRED; } group.SetFieldFlags(fieldFlags); stamper.AddAnnotation(group, 1); }); return(curY); }
public virtual void RemoveKidFromIndirectKidsArrayTest() { String inputFile = "in_removeKidFromIndirectKidsArrayTest.pdf"; String outputFile = "removeKidFromIndirectKidsArrayTest.pdf"; // Creating input document PdfDocument inDoc = new PdfDocument(new PdfWriter(DESTINATION_DIR + inputFile)); inDoc.AddNewPage(); PdfFormField root = PdfFormField.CreateEmptyField(inDoc); root.SetFieldName("root"); PdfFormField child = PdfFormField.CreateEmptyField(inDoc); child.SetFieldName("child"); root.AddKid(child); PdfAcroForm.GetAcroForm(inDoc, true).AddField(root); // make kids array indirect PdfAcroForm.GetAcroForm(inDoc, true).GetField("root").GetKids().MakeIndirect(inDoc); inDoc.Close(); // Creating stamping document PdfReader reader = new PdfReader(DESTINATION_DIR + inputFile); PdfWriter writer = new PdfWriter(DESTINATION_DIR + outputFile); PdfDocument outputDoc = new PdfDocument(reader, writer, new StampingProperties().UseAppendMode()); PdfAcroForm.GetAcroForm(outputDoc, true).RemoveField("root.child"); outputDoc.Close(); CompareWithCmp(outputFile); }
// --------------------------------------------------------------------------- /** * @see com.lowagie.text.pdf.PdfPCellEvent#cellLayout( * com.lowagie.text.pdf.PdfPCell, * com.lowagie.text.Rectangle, * com.lowagie.text.pdf.PdfContentByte[] * ) */ public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb) { parent.AddKid(kid); kid.SetWidget( new Rectangle(rect.GetLeft(padding), rect.GetBottom(padding), rect.GetRight(padding), rect.GetTop(padding)), PdfAnnotation.HIGHLIGHT_INVERT ); }
protected void ManipulatePdf(String dest) { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); PdfFormField personal = PdfFormField.CreateEmptyField(pdfDoc); personal.SetFieldName("personal"); PdfTextFormField name = PdfFormField.CreateText(pdfDoc, new Rectangle(36, 760, 108, 30), "name", ""); personal.AddKid(name); PdfTextFormField password = PdfFormField.CreateText(pdfDoc, new Rectangle(150, 760, 300, 30), "password", ""); personal.AddKid(password); PdfAcroForm.GetAcroForm(pdfDoc, true).AddField(personal, pdfDoc.GetFirstPage()); pdfDoc.Close(); }
// --------------------------------------------------------------------------- /** * Creates a PDF document. */ public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); BaseFont bf = BaseFont.CreateFont(); PdfContentByte directcontent = writer.DirectContent; directcontent.BeginText(); directcontent.SetFontAndSize(bf, 12); directcontent.ShowTextAligned(Element.ALIGN_LEFT, "Married?", 36, 770, 0); directcontent.ShowTextAligned(Element.ALIGN_LEFT, "YES", 58, 750, 0); directcontent.ShowTextAligned(Element.ALIGN_LEFT, "NO", 102, 750, 0); directcontent.ShowTextAligned( Element.ALIGN_LEFT, "Name partner?", 36, 730, 0 ); directcontent.EndText(); PdfFormField married = PdfFormField.CreateRadioButton(writer, true); married.FieldName = "married"; married.ValueAsName = "yes"; Rectangle rectYes = new Rectangle(40, 766, 56, 744); RadioCheckField yes = new RadioCheckField(writer, rectYes, null, "yes"); yes.Checked = true; married.AddKid(yes.RadioField); Rectangle rectNo = new Rectangle(84, 766, 100, 744); RadioCheckField no = new RadioCheckField(writer, rectNo, null, "no"); no.Checked = false; married.AddKid(no.RadioField); writer.AddAnnotation(married); Rectangle rect = new Rectangle(40, 710, 200, 726); TextField partner = new TextField(writer, rect, "partner"); partner.BorderColor = GrayColor.GRAYBLACK; partner.BorderWidth = 0.5f; writer.AddAnnotation(partner.GetTextField()); } return(ms.ToArray()); } }
private PdfFormField MergeFieldsWithTheSameName(PdfFormField existingField, PdfFormField newField) { String fullFieldName = newField.GetFieldName().ToUnicodeString(); PdfString fieldName = newField.GetPdfObject().GetAsString(PdfName.T); newField.GetPdfObject().Remove(PdfName.T); newField.GetPdfObject().Remove(PdfName.P); existingField = formTo.GetField(fullFieldName); PdfArray kids = existingField.GetKids(); if (kids != null && !kids.IsEmpty()) { existingField.AddKid(newField); return(existingField); } existingField.GetPdfObject().Remove(PdfName.T); existingField.GetPdfObject().Remove(PdfName.P); formTo.GetFields().Remove(existingField.GetPdfObject()); PdfFormField mergedField = PdfFormField.CreateEmptyField(documentTo); mergedField.Put(PdfName.FT, existingField.GetFormType()).Put(PdfName.T, fieldName); PdfDictionary parent = existingField.GetParent(); if (parent != null) { mergedField.Put(PdfName.Parent, parent); PdfArray parentKids = parent.GetAsArray(PdfName.Kids); for (int i = 0; i < parentKids.Size(); i++) { PdfObject obj = parentKids.Get(i); if (obj == existingField.GetPdfObject()) { parentKids.Set(i, mergedField.GetPdfObject()); break; } } } kids = existingField.GetKids(); if (kids != null) { mergedField.Put(PdfName.Kids, kids); } mergedField.AddKid(existingField).AddKid(newField); PdfObject value = existingField.GetValue(); if (value != null) { mergedField.Put(PdfName.V, existingField.GetPdfObject().Get(PdfName.V)); } return(mergedField); }
/// <summary> /// Adds the field to page. /// </summary> /// <param name="pageNumber">The page number.</param> /// <param name="pdfStamper">The PDF stamper.</param> /// <param name="parentField">The parent field.</param> /// TODO Edit XML Comment Template for AddFieldToPage private void AddFieldToPage( int pageNumber, PdfStamper pdfStamper, PdfFormField parentField) { var rectangle = new Rectangle( Field.LeftX, Field.TopY, Field.RightX, Field.BottomY); var textField = new TextField(pdfStamper.Writer, rectangle, null); var childField = textField.GetTextField(); parentField.AddKid(childField); childField.PlaceInPage = pageNumber; }
public virtual void AddFieldWithKidsTest() { PdfDocument pdfDoc = new PdfDocument(new PdfWriter(new ByteArrayOutputStream())); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfFormField root = PdfFormField.CreateEmptyField(pdfDoc); root.SetFieldName("root"); PdfFormField child = PdfFormField.CreateEmptyField(pdfDoc); child.SetFieldName("child"); root.AddKid(child); PdfTextFormField text1 = PdfFormField.CreateText(pdfDoc, new Rectangle(100, 700, 200, 20), "text1", "test" ); child.AddKid(text1); form.AddField(root); NUnit.Framework.Assert.AreEqual(3, form.GetFormFields().Count); }
public virtual void PdfA1DocWithPdfA1ButtonFieldTest() { String name = "pdfA1DocWithPdfA1ButtonField"; String fileName = destinationFolder + name + ".pdf"; String cmp = sourceFolder + "cmp/PdfAFormFieldTest/cmp_pdfA1DocWithPdfA1ButtonField.pdf"; Stream @is = new FileStream(sourceFolder + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read); PdfAConformanceLevel conformanceLevel = PdfAConformanceLevel.PDF_A_1B; PdfADocument pdfDoc = new PdfADocument(new PdfWriter(fileName), conformanceLevel, new PdfOutputIntent("Custom" , "", "http://www.color.org", "sRGB IEC61966-2.1", @is)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); PdfFormField emptyField = PdfFormField.CreateEmptyField(pdfDoc, conformanceLevel).SetFieldName("empty"); emptyField.AddKid(PdfFormField.CreateButton(pdfDoc, new Rectangle(36, 756, 20, 20), PdfAnnotation.PRINT, conformanceLevel ).SetFieldName("button").SetValue("hello")); form.AddField(emptyField); pdfDoc.Close(); NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(fileName, cmp, destinationFolder)); NUnit.Framework.Assert.IsNull(new VeraPdfValidator().Validate(fileName)); }
public void AddFields() { PdfContentByte cb = writer.DirectContent; Font _bf = new Font(Font.FontFamily.HELVETICA, 9); PdfFormField _radioGroup = PdfFormField.CreateRadioButton(writer, true); _radioGroup.FieldName = "language_gc"; _radioGroup.PlaceInPage = 0; Rectangle _rect; RadioCheckField _radioG; PdfFormField _radioField1; for (int i = 0; i < LANGUAGES_gc.Length; i++) { _rect = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40); _radioG = new RadioCheckField(writer, _rect, null, LANGUAGES_gc[i]) { BackgroundColor = new GrayColor(0.8f), BorderColor = GrayColor.BLACK, CheckType = RadioCheckField.TYPE_CIRCLE }; _radioField1 = _radioG.RadioField; _radioGroup.AddKid(_radioField1); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase(LANGUAGES_gc[i], new Font(Font.FontFamily.HELVETICA, 18)), 70, 790 - i * 40, 0); } writer.AddAnnotation(_radioGroup); cb = writer.DirectContent; TextField _text = new TextField(writer, new Rectangle(ConvertX(103), ConvertY(190), ConvertX(182), ConvertY(199)), "g1"); _text.Alignment = Element.ALIGN_CENTER; _text.Options = TextField.MULTILINE; _text.Text = "abc"; PdfFormField textbox = _text.GetTextField(); textbox.PlaceInPage = 1; writer.AddAnnotation(textbox); cb = writer.DirectContentUnder; table.WriteSelectedRows(0, -1, ConvertX(25), ConvertY(133), cb); idTable.WriteSelectedRows(0, -1, ConvertX(25), ConvertY(205), cb); }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); // step 3 document.Open(); // step 4 PdfContentByte cb = writer.DirectContent; BaseFont bf = BaseFont.CreateFont( BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED ); PdfFormField radiogroup = PdfFormField.CreateRadioButton( writer, true ); radiogroup.FieldName = "language"; Rectangle rect = new Rectangle(40, 806, 60, 788); RadioCheckField radio; PdfFormField radiofield; for (int page = 0; page < LANGUAGES.Length;) { radio = new RadioCheckField(writer, rect, null, LANGUAGES[page]); radio.BackgroundColor = new GrayColor(0.8f); radiofield = radio.RadioField; radiofield.PlaceInPage = ++page; radiogroup.AddKid(radiofield); } writer.AddAnnotation(radiogroup); for (int i = 0; i < LANGUAGES.Length; i++) { cb.BeginText(); cb.SetFontAndSize(bf, 18); cb.ShowTextAligned(Element.ALIGN_LEFT, LANGUAGES[i], 70, 790, 0); cb.EndText(); document.NewPage(); } } }
/** * Add the child field to the parent, and sets the coordinates of the child field. */ public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb) { parent.AddKid(kid); kid.SetWidget(new Rectangle(rect.GetLeft(padding), rect.GetTop(padding + 1f) - 11f, rect.GetRight(padding), rect.GetTop(padding + 1f)), PdfAnnotation.HighlightInvert); //kid.SetWidget(new Rectangle(rect.Left, rect.Bottom + size, rect.Width, rect.Height - size), PdfAnnotation.HighlightInvert); }
public virtual void Copy(PdfPage fromPage, PdfPage toPage) { if (documentFrom != fromPage.GetDocument()) { documentFrom = fromPage.GetDocument(); formFrom = PdfAcroForm.GetAcroForm(documentFrom, false); } if (documentTo != toPage.GetDocument()) { documentTo = toPage.GetDocument(); formTo = PdfAcroForm.GetAcroForm(documentTo, true); if (formFrom != null) { //duplicate AcroForm dictionary IList <PdfName> excludedKeys = new List <PdfName>(); excludedKeys.Add(PdfName.Fields); excludedKeys.Add(PdfName.DR); PdfDictionary dict = formFrom.GetPdfObject().CopyTo(documentTo, excludedKeys, false); formTo.GetPdfObject().MergeDifferent(dict); } } IList <PdfDictionary> usedParents = new List <PdfDictionary>(); if (formFrom != null) { IDictionary <String, PdfFormField> fieldsFrom = formFrom.GetFormFields(); if (fieldsFrom.Count > 0) { IDictionary <String, PdfFormField> fieldsTo = formTo.GetFormFields(); IList <PdfAnnotation> annots = toPage.GetAnnotations(); foreach (PdfAnnotation annot in annots) { if (annot.GetSubtype().Equals(PdfName.Widget)) { PdfDictionary parent = annot.GetPdfObject().GetAsDictionary(PdfName.Parent); if (parent != null) { PdfString parentName = parent.GetAsString(PdfName.T); if (parentName == null) { continue; } if (!usedParents.Contains(parent)) { PdfFormField field = PdfFormField.MakeFormField(parent, toPage.GetDocument()); field.GetKids().Clear(); formTo.AddField(field, toPage); usedParents.Add(parent); field.AddKid((PdfWidgetAnnotation)annot); } else { parent.GetAsArray(PdfName.Kids).Add(annot.GetPdfObject()); } } else { PdfString annotName = annot.GetPdfObject().GetAsString(PdfName.T); String annotNameString = null; if (annotName != null) { annotNameString = annotName.ToUnicodeString(); } if (annotNameString != null && fieldsFrom.ContainsKey(annotNameString)) { PdfFormField field = PdfFormField.MakeFormField(annot.GetPdfObject(), toPage.GetDocument()); if (fieldsTo.ContainsKey(annotNameString)) { field = MergeFieldsWithTheSameName(field, fieldsTo.Get(annotNameString)); ILogger logger = LoggerFactory.GetLogger(typeof(PdfPageFormCopier)); logger.Warn(String.Format(LogMessageConstant.DOCUMENT_ALREADY_HAS_FIELD, annotNameString)); } formTo.AddField(field, null); } } } } } } }
// --------------------------------------------------------------------------- /** * Creates a PDF document. */ public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); jsString = File.ReadAllText( Path.Combine(Utility.ResourceJavaScript, RESOURCE) ); writer.AddJavaScript(jsString); PdfContentByte canvas = writer.DirectContent; Font font = new Font(Font.FontFamily.HELVETICA, 18); Rectangle rect; PdfFormField field; PdfFormField radiogroup = PdfFormField.CreateRadioButton(writer, true); radiogroup.FieldName = "language"; RadioCheckField radio; for (int i = 0; i < LANGUAGES.Length; i++) { rect = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40); radio = new RadioCheckField(writer, rect, null, LANGUAGES[i]); radio.BorderColor = GrayColor.GRAYBLACK; radio.BackgroundColor = GrayColor.GRAYWHITE; radio.CheckType = RadioCheckField.TYPE_CIRCLE; field = radio.RadioField; radiogroup.AddKid(field); ColumnText.ShowTextAligned( canvas, Element.ALIGN_LEFT, new Phrase(LANGUAGES[i], font), 70, 790 - i * 40, 0 ); } writer.AddAnnotation(radiogroup); PdfAppearance[] onOff = new PdfAppearance[2]; onOff[0] = canvas.CreateAppearance(20, 20); onOff[0].Rectangle(1, 1, 18, 18); onOff[0].Stroke(); onOff[1] = canvas.CreateAppearance(20, 20); onOff[1].SetRGBColorFill(255, 128, 128); onOff[1].Rectangle(1, 1, 18, 18); onOff[1].FillStroke(); onOff[1].MoveTo(1, 1); onOff[1].LineTo(19, 19); onOff[1].MoveTo(1, 19); onOff[1].LineTo(19, 1); onOff[1].Stroke(); RadioCheckField checkbox; for (int i = 0; i < LANGUAGES.Length; i++) { rect = new Rectangle(180, 806 - i * 40, 200, 788 - i * 40); checkbox = new RadioCheckField(writer, rect, LANGUAGES[i], "on"); // checkbox.CheckType = RadioCheckField.TYPE_CHECK; field = checkbox.CheckField; field.SetAppearance( PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0] ); field.SetAppearance( PdfAnnotation.APPEARANCE_NORMAL, "On", onOff[1] ); writer.AddAnnotation(field); ColumnText.ShowTextAligned( canvas, Element.ALIGN_LEFT, new Phrase(LANGUAGES[i], font), 210, 790 - i * 40, 0 ); } rect = new Rectangle(300, 806, 370, 788); PushbuttonField button = new PushbuttonField(writer, rect, "Buttons"); button.BackgroundColor = new GrayColor(0.75f); button.BorderColor = GrayColor.GRAYBLACK; button.BorderWidth = 1; button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED; button.TextColor = GrayColor.GRAYBLACK; button.FontSize = 12; button.Text = "Push me"; button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT; button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS; button.ProportionalIcon = true; button.IconHorizontalAdjustment = 0; button.Image = Image.GetInstance( Path.Combine(Utility.ResourceImage, IMAGE) ); field = button.Field; field.Action = PdfAction.JavaScript("this.showButtonState()", writer); writer.AddAnnotation(field); } return(ms.ToArray()); } }
private PdfFormField MergeFieldsWithTheSameName(PdfFormField newField) { String fullFieldName = newField.GetFieldName().ToUnicodeString(); PdfString fieldName = newField.GetPdfObject().GetAsString(PdfName.T); logger.Warn(MessageFormatUtil.Format(iText.IO.LogMessageConstant.DOCUMENT_ALREADY_HAS_FIELD, fullFieldName )); PdfFormField existingField = formTo.GetField(fullFieldName); if (existingField.IsFlushed()) { int index = 0; do { index++; newField.SetFieldName(fieldName.ToUnicodeString() + "_#" + index); fullFieldName = newField.GetFieldName().ToUnicodeString(); }while (formTo.GetField(fullFieldName) != null); return(newField); } newField.GetPdfObject().Remove(PdfName.T); newField.GetPdfObject().Remove(PdfName.P); formTo.GetFields().Remove(existingField.GetPdfObject()); PdfArray kids = existingField.GetKids(); if (kids != null && !kids.IsEmpty()) { existingField.AddKid(newField); return(existingField); } existingField.GetPdfObject().Remove(PdfName.T); existingField.GetPdfObject().Remove(PdfName.P); PdfFormField mergedField = PdfFormField.CreateEmptyField(documentTo); mergedField.Put(PdfName.FT, existingField.GetFormType()).Put(PdfName.T, fieldName); PdfDictionary parent = existingField.GetParent(); if (parent != null) { mergedField.Put(PdfName.Parent, parent); PdfArray parentKids = parent.GetAsArray(PdfName.Kids); for (int i = 0; i < parentKids.Size(); i++) { PdfObject obj = parentKids.Get(i); if (obj == existingField.GetPdfObject()) { parentKids.Set(i, mergedField.GetPdfObject()); break; } } } kids = existingField.GetKids(); if (kids != null) { mergedField.Put(PdfName.Kids, kids); } mergedField.AddKid(existingField).AddKid(newField); PdfObject value = existingField.GetPdfObject().Get(PdfName.V); if (value != null) { mergedField.Put(PdfName.V, existingField.GetPdfObject().Get(PdfName.V)); } return(mergedField); }
public virtual void Copy(PdfPage fromPage, PdfPage toPage) { if (documentFrom != fromPage.GetDocument()) { documentFrom = fromPage.GetDocument(); formFrom = PdfAcroForm.GetAcroForm(documentFrom, false); } if (documentTo != toPage.GetDocument()) { documentTo = toPage.GetDocument(); formTo = PdfAcroForm.GetAcroForm(documentTo, true); } if (formFrom != null) { //duplicate AcroForm dictionary IList <PdfName> excludedKeys = new List <PdfName>(); excludedKeys.Add(PdfName.Fields); excludedKeys.Add(PdfName.DR); PdfDictionary dict = formFrom.GetPdfObject().CopyTo(documentTo, excludedKeys, false); formTo.GetPdfObject().MergeDifferent(dict); } if (formFrom != null) { IDictionary <String, PdfFormField> fieldsFrom = formFrom.GetFormFields(); if (fieldsFrom.Count > 0) { IDictionary <String, PdfFormField> fieldsTo = formTo.GetFormFields(); IList <PdfAnnotation> annots = toPage.GetAnnotations(); foreach (PdfAnnotation annot in annots) { if (annot.GetSubtype().Equals(PdfName.Widget)) { PdfDictionary parent = annot.GetPdfObject().GetAsDictionary(PdfName.Parent); if (parent != null) { PdfFormField parentField = GetParentField(parent, documentTo); PdfString parentName = parentField.GetFieldName(); if (parentName == null) { continue; } if (!fieldsTo.ContainsKey(parentName.ToUnicodeString())) { PdfFormField field = CreateParentFieldCopy(annot.GetPdfObject(), documentTo); PdfArray kids = field.GetKids(); field.GetPdfObject().Remove(PdfName.Kids); formTo.AddField(field, toPage); field.GetPdfObject().Put(PdfName.Kids, kids); } else { PdfFormField field = PdfFormField.MakeFormField(annot.GetPdfObject(), documentTo); PdfString fieldName = field.GetFieldName(); if (fieldName != null) { PdfFormField existingField = fieldsTo.Get(fieldName.ToUnicodeString()); if (existingField != null) { PdfFormField clonedField = PdfFormField.MakeFormField(field.GetPdfObject().Clone().MakeIndirect(documentTo ), documentTo); toPage.GetPdfObject().GetAsArray(PdfName.Annots).Add(clonedField.GetPdfObject()); toPage.RemoveAnnotation(annot); MergeFieldsWithTheSameName(existingField, clonedField); } else { HashSet <String> existingFields = new HashSet <String>(); GetAllFieldNames(formTo.GetFields(), existingFields); AddChildToExistingParent(annot.GetPdfObject(), existingFields); } } else { if (parentField.GetKids().Contains(field.GetPdfObject())) { field = PdfFormField.MakeFormField(field.GetPdfObject().Clone().MakeIndirect(documentTo), documentTo); toPage.GetPdfObject().GetAsArray(PdfName.Annots).Add(field.GetPdfObject()); toPage.RemoveAnnotation(annot); } parentField.AddKid(field); } } } else { PdfString annotName = annot.GetPdfObject().GetAsString(PdfName.T); String annotNameString = null; if (annotName != null) { annotNameString = annotName.ToUnicodeString(); } if (annotNameString != null && fieldsFrom.ContainsKey(annotNameString)) { PdfFormField field = fieldsTo.Get(annotNameString); if (field != null) { PdfDictionary clonedAnnot = (PdfDictionary)annot.GetPdfObject().Clone().MakeIndirect(documentTo); toPage.GetPdfObject().GetAsArray(PdfName.Annots).Add(clonedAnnot); toPage.RemoveAnnotation(annot); field = MergeFieldsWithTheSameName(field, PdfFormField.MakeFormField(clonedAnnot, toPage.GetDocument())); logger.Warn(String.Format(LogMessageConstant.DOCUMENT_ALREADY_HAS_FIELD, annotNameString)); PdfArray kids = field.GetKids(); field.GetPdfObject().Remove(PdfName.Kids); formTo.AddField(field, toPage); field.GetPdfObject().Put(PdfName.Kids, kids); } else { formTo.AddField(PdfFormField.MakeFormField(annot.GetPdfObject(), documentTo), null); } } } } } } } }
public TestCreatePDF() { filenameBlank = filename.Replace(".", "_Blank."); FileStream fs = new System.IO.FileStream(filenameBlank, System.IO.FileMode.Create); writer = PdfWriter.GetInstance(doc, fs); doc.Open(); cb = writer.DirectContent; Rectangle rect = new Rectangle(50, 700, 300, 600) { BorderWidth = .25f, Border = 255 }; cb.Rectangle(rect); cb.Stroke(); //Add text Font font3 = new Font(FontFactory.GetFont(FontFactory.HELVETICA, 1000, Font.NORMAL, BaseColor.BLACK)); Chunk chunk = new Chunk("Roopesh", new Font(FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.NORMAL, BaseColor.BLUE))); Phrase phrase = new Phrase(chunk); ColumnText ctext = new ColumnText(cb); ctext.SetSimpleColumn(rect.Left + 5, rect.Top, rect.Right, rect.Bottom); ctext.SetText(phrase); ctext.Go(); this.doc.Close(); GetReader(); //Add TextBox rect = new Rectangle(rect.Left, rect.Top - 100, rect.Right, rect.Bottom - 100); TextField tf = new TextField(writer, rect, "text1") { Alignment = Element.ALIGN_LEFT | Element.ALIGN_TOP, BorderColor = BaseColor.BLACK, BorderStyle = PdfBorderDictionary.STYLE_SOLID, Text = "TextField" }; stamper.AddAnnotation(tf.GetTextField(), 1); //Add Radio rect = new Rectangle(rect.Left, rect.Top - 100, rect.Right, rect.Bottom - 25); PdfFormField group = PdfFormField.CreateRadioButton(writer, true); group.FieldName = "grp1"; for (int i = 0; i < 5; i++) { Rectangle radioRect = new Rectangle(rect.Left + i * 25, rect.Top, rect.Left + (i + 1) * 25, rect.Bottom); RadioCheckField radioField = new RadioCheckField(writer, radioRect, "chk" + i.ToString(), i.ToString()) { BorderColor = GrayColor.BLACK, CheckType = RadioCheckField.TYPE_CIRCLE, BorderStyle = PdfBorderDictionary.STYLE_SOLID }; group.AddKid(radioField.RadioField); } //group.SetAdditionalActions(PdfName.E, PdfAction.JavaScript("app.alert(validate);",writer)); stamper.AddAnnotation(group, 1); //Add submit button rect = new Rectangle(rect.Left, rect.Top - 100, rect.Right, rect.Bottom - 25); PushbuttonField button = new PushbuttonField(writer, rect, "postSubmit") { FontSize = 8, BackgroundColor = BaseColor.LIGHT_GRAY, BorderColor = GrayColor.BLACK, BorderWidth = 1f, BorderStyle = PdfBorderDictionary.STYLE_BEVELED, TextColor = GrayColor.GREEN, Text = "Submit", Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT }; PdfFormField field = button.Field; String javascript = "validate();"; field.Action = PdfAction.JavaScript(javascript, writer); //field.Action = PdfAction.CreateSubmitForm( @"*****@*****.**", null, PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_INCLUDE_NO_VALUE_FIELDS); stamper.AddAnnotation(field, 1); PdfAcroForm f = new PdfAcroForm(writer); //Add common Javascript code writer.AddJavaScript("var requiredFields = ['text1', 'grp1'];"); string validateFunction = "function validate () { " + " for (i=0; i<requiredFields.length; i++) {" + " var grp = this.getField(requiredFields[i]); if (!grp || grp.value === null || grp.value == ''|| grp.value=='Off') { " + " app.alert('please select this '+ requiredFields[i]); return false; }}" + "return true}"; writer.AddJavaScript(validateFunction); //Close all the streams stamper.Close(); reader.Close(); doc.Close(); }
public ValueCreationBlock() { filenameBlank = filename.Replace(".", "_Blank."); FileStream fs = new System.IO.FileStream(filenameBlank, System.IO.FileMode.Create); writer = PdfWriter.GetInstance(doc, fs); doc.Open(); cb = writer.DirectContent; BaseFont bfHelvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false); Font helvetica12 = new Font(bfHelvetica, 12, Font.NORMAL, BaseColor.BLACK); PdfPTable table = new PdfPTable(2); table.TotalWidth = 570f; table.LockedWidth = true; //relative col widths in proportions - 1/3 and 2/3 float[] widths = new float[] { 2f, 3f }; table.SetWidths(widths); table.HorizontalAlignment = Element.ALIGN_CENTER; PdfPCell cell1 = new PdfPCell(new Phrase("Value Creation and Impact", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.WHITE))); cell1.PaddingLeft = 10; cell1.BackgroundColor = PDFColor.BCGGreen; cell1.Colspan = 3; cell1.Border = PdfPCell.NO_BORDER; cell1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right table.AddCell(cell1); PdfPTable nested = new PdfPTable(1); //nested.TotalWidth = 270f; //nested.LockedWidth = true; //float[] widthforcol = new float[] { 100f, 170f}; //nested.SetWidths(widthforcol); PdfPCell cell2 = new PdfPCell(new Phrase("Develops clear recommendations with an action bias", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell2.PaddingLeft = 10; //cell2.Colspan = 2; cell2.BackgroundColor = BaseColor.LIGHT_GRAY; cell2.Border = PdfPCell.NO_BORDER; cell2.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell2); PdfPCell cell3 = new PdfPCell(new Phrase("Networks within client organization to understand agenda", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell3.PaddingLeft = 10; //cell3.Colspan = 2; cell3.BackgroundColor = BaseColor.LIGHT_GRAY; cell3.Border = PdfPCell.NO_BORDER; cell3.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell3); PdfPCell cell4 = new PdfPCell(new Phrase("Is able to assess implementation challenges", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell4.PaddingLeft = 10; //cell4.Colspan = 2; cell4.BackgroundColor = BaseColor.LIGHT_GRAY; cell4.Border = PdfPCell.NO_BORDER; cell4.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell4); PdfPCell cell5 = new PdfPCell(new Phrase("Applies expertise to generate superior and sustainable results for client; is committed to making change happen", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell5.PaddingLeft = 10; //cell5.Colspan = 2; cell5.BackgroundColor = BaseColor.LIGHT_GRAY; cell5.Border = PdfPCell.NO_BORDER; cell5.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell5); PdfPCell cell6 = new PdfPCell(new Phrase("Effectively transfers capabilities to client teams", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell6.PaddingLeft = 10; //cell6.Colspan = 2; cell6.BackgroundColor = BaseColor.LIGHT_GRAY; cell6.Border = PdfPCell.NO_BORDER; cell6.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell6); //Rectangle rect = new iTextSharp.text.Rectangle(10, 20, 30, 40); //var rf1 = new RadioCheckField(writer, rect, "cellRadioBox", "on"); //rf1.CheckType = RadioCheckField.TYPE_CHECK; //PdfFormField field = rf1.CheckField; string[] labels = { "NA", "1", "2", "3", "4", "5" }; BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); // create a radio field spanning different pages PdfFormField radiogroup = PdfFormField.CreateRadioButton(writer, true); radiogroup.FieldName = "language"; //Rectangle rect = new Rectangle(40, 606, 60, 588); RadioCheckField radio; PdfFormField radiofield; Rectangle rect; for (int i = 0; i < labels.Length; ++i) { rect = new Rectangle(50 + i * 30, 705, 50 + (i + 1) * 30, 695);//PDFDocPageSize.RIGHT //rect = new Rectangle(40, 606, 60, 588); radio = new RadioCheckField(writer, rect, null, labels[i]); radio.BackgroundColor = new GrayColor(0.8f); radiofield = radio.RadioField; radiofield.PlaceInPage = 1; //radiofield.PlaceInPage= ++page; radiogroup.AddKid(radiofield); } var radioEvents = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, radiogroup); PdfPCell radioCell = new PdfPCell(); radioCell.CellEvent = radioEvents; nested.AddCell(radioCell); PdfPCell nesthousing = new PdfPCell(nested); nesthousing.Padding = 0f; table.AddCell(nesthousing); TextField textfield = new TextField(writer, new iTextSharp.text.Rectangle(10, 20, 30, 40), "cellTextBox"); PdfPCell tbCell = new PdfPCell(new Phrase(" ", helvetica12)); iTextSharp.text.pdf.events.FieldPositioningEvents events = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, textfield.GetTextField()); tbCell.CellEvent = events; table.AddCell(tbCell); doc.Add(table); this.doc.Close(); GetReader(); //Add common Javascript code writer.AddJavaScript("var requiredFields = ['text1', 'grp1'];"); string validateFunction = "function validate () { " + " for (i=0; i<requiredFields.length; i++) {" + " var grp = this.getField(requiredFields[i]); if (!grp || grp.value === null || grp.value == ''|| grp.value=='Off') { " + " app.alert('please select this '+ requiredFields[i]); return false; }}" + "return true}"; writer.AddJavaScript(validateFunction); //Close all the streams stamper.Close(); reader.Close(); doc.Close(); }