Checking off pdf checkbox with itextsharp - pdf

I've tried so many different ways, but I can't get the check box to be checked! Here's what I've tried:
var reader = new iTextSharp.text.pdf.PdfReader(originalFormLocation);
using (var stamper = new iTextSharp.text.pdf.PdfStamper(reader,ms)) {
var formFields = stamper.AcroFields;
formFields.SetField("IsNo", "1");
formFields.SetField("IsNo", "true");
formFields.SetField("IsNo", "On");
}
None of them work. Any ideas?

You shouldn't "guess" for the possible values. You need to use a value that is stored in the PDF. Try the CheckBoxValues example to find these possible values:
public String getCheckboxValue(String src, String name) throws IOException {
PdfReader reader = new PdfReader(SRC);
AcroFields fields = reader.getAcroFields();
// CP_1 is the name of a check box field
String[] values = fields.getAppearanceStates("IsNo");
StringBuffer sb = new StringBuffer();
for (String value : values) {
sb.append(value);
sb.append('\n');
}
return sb.toString();
}
Or take a look at the PDF using RUPS. Go to the widget annotation and look for the normal (/N) appearance (AP) states. In my example they are /Off and /Yes:

Related

Fill XFA without breaking usage rights

I have an XFA form that I can successfully fill in by extracting the XML modifying and writing back. Works great if you have the full Adobe Acrobat, but fails with Adobe Reader. I have seen various questions on the same thing with answers but they were some time ago so updating an XFA that is readable by Adobe Reader may no longer be doable?
I use this code below and I've utilised the StampingProperties of append as in the iText example but still failing. I'm using iText 7.1.15.
//open file and write to temp one
PdfDocument pdf = new(new PdfReader(FileToProcess), new PdfWriter(NewPDF), new StampingProperties().UseAppendMode());
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
XfaForm xfa = form.GetXfaForm();
XElement node = xfa.GetDatasetsNode();
IEnumerable<XNode> list = node.Nodes();
foreach (XNode item in list)
{
if (item is XElement element && "data".Equals(element.Name.LocalName))
{
node = element;
break;
}
}
XmlWriterSettings settings = new() { Indent = true };
using XmlWriter writer = XmlWriter.Create(XMLOutput, settings);
{
node.WriteTo(writer);
writer.Flush();
writer.Close();
}
//We now how to strip an extra xfa line if updating
if(update)
{
string TempXML= CSTrackerHelper.MakePath($"{AppContext.BaseDirectory}Temp", $"{Guid.NewGuid()}.XML");
StreamReader fsin = new(XMLOutput);
StreamWriter fsout = new(TempXML);
string linedata = string.Empty;
int cnt = 0;
while (!fsin.EndOfStream)
{
if (cnt != 3 && linedata != string.Empty)
{
fsout.WriteLine(linedata);
}
linedata = fsin.ReadLine();
cnt++;
}
fsout.Close();
fsin.Close();
XMLOutput = TempXML;
}
xlogger.Info("Populating pdf fields");
//Now loop through our field data and update the XML
XmlDocument xmldoc = new();
xmldoc.Load(XMLOutput);
XmlNamespaceManager xmlnsManager = new(xmldoc.NameTable);
xmlnsManager.AddNamespace("xfa", #"http://www.xfa.org/schema/xfa-data/1.0/");
string[] FieldValues;
string[] MultiNodes;
foreach (KeyValuePair<string, DocumentFieldData> v in DocumentData.FieldData)
{
if (!string.IsNullOrEmpty(v.Value.Field))
{
FieldValues = v.Value.Field.Contains(";") ? v.Value.Field.Split(';') : (new string[] { v.Value.Field });
foreach (string FValue in FieldValues)
{
XmlNodeList aNodes;
if (FValue.Contains("{"))
{
aNodes = xmldoc.SelectNodes(FValue.Substring(0, FValue.LastIndexOf("{")), xmlnsManager);
if (aNodes.Count > 1)
{
//We have a multinode
MultiNodes = FValue.Split('{');
int NodeIndex = int.Parse(MultiNodes[1].Replace("}", ""));
aNodes[NodeIndex].InnerText = v.Value.Data;
}
}
else
{
aNodes = xmldoc.SelectNodes(FValue, xmlnsManager);
if (aNodes.Count >= 1)
{
aNodes[0].InnerText = v.Value.Data;
}
}
}
}
}
xmldoc.Save(XMLOutput);
//Now we've updated the XML apply it to the pdf
xfa.FillXfaForm(new FileStream(XMLOutput, FileMode.Open, FileAccess.Read));
xfa.Write(pdf);
pdf.Close();
FYI I've also tried to set a field directly also with the same results.
PdfReader preader = new PdfReader(source);
PdfDocument pdfDoc=new PdfDocument(preader, new PdfWriter(dest), new StampingProperties().UseAppendMode());
PdfAcroForm pdfForm = PdfAcroForm.GetAcroForm(pdfDoc, true);
XfaForm xform = pdfForm.GetXfaForm();
xform.SetXfaFieldValue("VRM[0].CoverPage[0].Wrap2[0].Table[0].CSID[0]", "Test");
xform.Write(pdfForm);
pdfDoc.Close();
If anyone has any ideas it would be appreciated.
Cheers
I ran into a very similar issue. I was attempting to auto fill an XFA that was password protected while not breaking the certificate or usage rights (it allowed filling). iText7 seems to have made this not possible for legal/practical reasons, however it is still very much possible with iText5. I wrote the following working codeusing iTextSharp (C# version if iText5):
using iTextSharp.text;
using iTextSharp.text.pdf;
string pathToRead = "/Users/home/Desktop/c#pdfParser/encrypted_empty.pdf";
string pathToSave = "/Users/home/Desktop/c#pdfParser/xfa_encrypted_filled.pdf";
string data = "/Users/home/Desktop/c#pdfParser/sample_data.xml";
FillByItextSharp5(pathToRead, pathToSave, data);
static void FillByItextSharp5(string pathToRead, string pathToSave, string data)
{
using (FileStream pdf = new FileStream(pathToRead, FileMode.Open))
using (FileStream xml = new FileStream(data, FileMode.Open))
using (FileStream filledPdf = new FileStream(pathToSave, FileMode.Create))
{
PdfReader.unethicalreading = true;
PdfReader pdfReader = new PdfReader(pdf);
PdfStamper stamper = new PdfStamper(pdfReader, filledPdf, '\0', true);
stamper.AcroFields.Xfa.FillXfaForm(xml, true);
stamper.Close();
pdfReader.Close();
}
}
PdfStamper stamper = new PdfStamper(pdfReader, filledPdf, '\0', true)
you have to use this line.

Watermarking pdf on document upload

I want to add a functionality of adding a watermark using itextSharp library to the pdf document that is being added to the library. For this I created an event listener that is triggered when item is being added. The code is as follows :
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
namespace ProjectPrac.WaterMarkOnUpload
{
/// <summary>
/// List Item Events
/// </summary>
public class WaterMarkOnUpload : SPItemEventReceiver
{
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
string watermarkedFile = "Watermarked.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader("C:\\Users\\Desktop\\Hello.pdf"); //THE RELATIVE PATH
using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
// Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
// Getting total number of pages of the Existing Document
int pageCount = reader1.NumberOfPages;
// Create New Layer for Watermark
PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
// Loop through each Page
for (int i = 1; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader1.GetPageSize(i);
// Get the ContentByte object
PdfContentByte cb = stamper.GetUnderContent(i);
// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer);
cb.SetFontAndSize(BaseFont.CreateFont(
BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
PdfGState gState = new PdfGState();
gState.FillOpacity = 0.25f;
cb.SetGState(gState);
cb.SetColorFill(BaseColor.BLACK);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Confidential", rect.Width / 2, rect.Height / 2, 45f);
cb.EndText();
// Close the layer
cb.EndLayer();
}
}
}
I want to know how to add the path without hardcoding it here :
PdfReader reader1 = new PdfReader("C:\\Users\\Desktop\\Hello.pdf"); //THE RELATIVE PATH
And then uploading the watermarked document to the library and not the original pdf.
I know that it can also be done through workflow but I am pretty new to sharepoint. So if at all you have an answer that has workflow in it please give the link that explains the workflow for automating the pdf watermarking.
You don't need to have workflow to achieve what you are looking for:
First, use ItemAdded event instead of ItemAdding. Then you can access SPFile associated with updated list item.
public override void ItemAdded(SPItemEventProperties properties)
{
var password = string.Empty; //or you put some password handling
SPListItem listItemToFile = properties.Listitem;
SPFile pdfOriginalFile = listItemToFile.File;
//get byte[] of uploaded file
byte[] contentPdfOriginalFile = pdfOriginalFile.OpenBinary();
//create reader from byte[]
var pdfReader = new PdfReader(new RandomAccessFileOrArray(contentPdfOriginalFile), password);
using (var ms = new MemoryStream()) {
using (var stamper = new PdfStamper(pdfReader, ms, '\0', true)) {
// do your watermarking stuff
...
// resuming SP stuff
}
var watermarkedPdfContent = ms.ToArray();
base.EventFiringEnabled = false; //to prevent other events being fired
var folder = pdfOriginalFile.ParentFolder;//you want to upload to the same place
folder.Files.Add(contentPdfOriginalFile.Name, fs.ToArray(),true);
base.EventFiringEnabled = true;
}
}
I probably did a typo or two since I didn't run this code. However, it should give you an idea.

iTextSharp - Using PDFAction.GotoLocalPage in Merged PDF

I have written some code that merges together multiple PDF's into a single PDF that I then display from the MemoryStream. This works great. What I need to do is add a table of contents to the end of the file with links to the start of each of the individual PDF's. I planned on doing this using the GotoLocalPage action which has an option for page numbers but it doesn't seem to work. If I change the action to the code below to one of the presset ones like PDFAction.FIRSTPAGE it works fine. Does this not work because I am using the PDFCopy object for the writer parameter of GotoLocalPage?
Document mergedDoc = new Document();
MemoryStream ms = new MemoryStream();
PdfCopy copy = new PdfCopy(mergedDoc, ms);
mergedDoc.Open();
MemoryStream tocMS = new MemoryStream();
Document tocDoc = null;
PdfWriter tocWriter = null;
for (int i = 0; i < filesToMerge.Length; i++)
{
string filename = filesToMerge[i];
PdfReader reader = new PdfReader(filename);
copy.AddDocument(reader);
// Initialise TOC document based off first file
if (i == 0)
{
tocDoc = new Document(reader.GetPageSizeWithRotation(1));
tocWriter = PdfWriter.GetInstance(tocDoc, tocMS);
tocDoc.Open();
}
// Create link for TOC, added random number of 3 for now
Chunk link = new Chunk(filename);
PdfAction action = PdfAction.GotoLocalPage(3, new PdfDestination(PdfDestination.FIT), copy);
link.SetAction(action);
tocDoc.Add(new Paragraph(link));
}
// Add TOC to end of merged PDF
tocDoc.Close();
PdfReader tocReader = new PdfReader(tocMS.ToArray());
copy.AddDocument(tocReader);
copy.Close();
displayPDF(ms.ToArray());
I guess an alternative would be to link to a named element (instead of page number) but I can't see how to add an 'invisible' element to the start of each file before adding to the merged document?
I would just go with two passes. In your first pass, do the merge as you are but also record the filename and page number it should link to. In your second pass, use a PdfStamper which will give you access to a ColumnText that you can use general abstractions like Paragraph in. Below is a sample that shows this off:
Since I don't have your documents, the below code creates 10 documents with a random number of pages each just for testing purposes. (You obviously don't need to do this part.) It also creates a simple dictionary with a fake file name as the key and the raw bytes from the PDF as a value. You have a true file collection to work with but you should be able to adapt that part.
//Create a bunch of files, nothing special here
//files will be a dictionary of names and the raw PDF bytes
Dictionary<string, byte[]> Files = new Dictionary<string, byte[]>();
var r = new Random();
for (var i = 1; i <= 10; i++) {
using (var ms = new MemoryStream()) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, ms)) {
doc.Open();
//Create a random number of pages
for (var j = 1; j <= r.Next(1, 5); j++) {
doc.NewPage();
doc.Add(new Paragraph(String.Format("Hello from document {0} page {1}", i, j)));
}
doc.Close();
}
}
Files.Add("File " + i.ToString(), ms.ToArray());
}
}
This next block merges the PDFs. This is mostly the same as your code except that instead of writing a TOC here I'm just keeping track of what I want to write in the future. Where I'm using file.value you'd use your full file path and where I'm using file.key you'd use your file's name instead.
//Dictionary of file names (for display purposes) and their page numbers
var pages = new Dictionary<string, int>();
//PDFs start at page 1
var lastPageNumber = 1;
//Will hold the final merged PDF bytes
byte[] mergedBytes;
//Most everything else below is standard
using (var ms = new MemoryStream()) {
using (var document = new Document()) {
using (var writer = new PdfCopy(document, ms)) {
document.Open();
foreach (var file in Files) {
//Add the current page at the previous page number
pages.Add(file.Key, lastPageNumber);
using (var reader = new PdfReader(file.Value)) {
writer.AddDocument(reader);
//Increment our current page index
lastPageNumber += reader.NumberOfPages;
}
}
}
}
mergedBytes = ms.ToArray();
}
This last block actually writes the TOC. If we use a PdfStamper we can create a ColumnText which allows us to use Paragraphs
//Will hold the final PDF
byte[] finalBytes;
using (var ms = new MemoryStream()) {
using (var reader = new PdfReader(mergedBytes)) {
using (var stamper = new PdfStamper(reader, ms)) {
//The page number to insert our TOC into
var tocPageNum = reader.NumberOfPages + 1;
//Arbitrarily pick one page to use as the size of the PDF
//Additional logic could be added or this could just be set to something like PageSize.LETTER
var tocPageSize = reader.GetPageSize(1);
//Arbitrary margin for the page
var tocMargin = 20;
//Create our new page
stamper.InsertPage(tocPageNum, tocPageSize);
//Create a ColumnText object so that we can use abstractions like Paragraph
var ct = new ColumnText(stamper.GetOverContent(tocPageNum));
//Set the working area
ct.SetSimpleColumn(tocPageSize.GetLeft(tocMargin), tocPageSize.GetBottom(tocMargin), tocPageSize.GetRight(tocMargin), tocPageSize.GetTop(tocMargin));
//Loop through each page
foreach (var page in pages) {
var link = new Chunk(page.Key);
var action = PdfAction.GotoLocalPage(page.Value, new PdfDestination(PdfDestination.FIT), stamper.Writer);
link.SetAction(action);
ct.AddElement(new Paragraph(link));
}
ct.Go();
}
}
finalBytes = ms.ToArray();
}

itext signing pdf

I'm currently developing an ERP application which uses iText for creating and signing PDF files. The idea is that the app can generate a PDF file with a bill, then use PdfStamper or any other class to sign it with a digital signature. Here's my code:
CREATING AND EDITING THE BILL
File f1 = null;
f1 = new File("myFilePath");
f1.delete();
if ((f1 != null) && (f1.createNewFile()))
{
//Here I call the procedure that creates the bill
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f1));
PdfFormField field = PdfFormField.createSignature(writer);
PdfSigner pdfSigner = new PdfSigner();
pdfSigner.setFileIn(f1.getAbsolutePath());
pdfSigner.setFileKey("myKeyPath.pfx");
pdfSigner.setFileKeyPassword("myPassword");
pdfSigner.setFileOut("myOutputPath");
if (pdfGenerator.factura(writer, pdfSigner, document))
{
//Here I show the File to the user
}
}
else
{
//Here I show an error
}
PROCEDURE "factura"
public boolean factura (PdfWriter writer, PdfSigner signer, Document document) throws NullPointerException
{
try
{
//Here I set a PdfPageEvent before attaching it to the PdfWriter
writer.setPageEvent(myPdfPageEvent);
document.open();
//Here I manipulate the Document to generate the bill
signer.signPdf();
document.close();
return true;
}
//catch 4 or 5 different types of exceptions and return false if needed
}
CLASS PdfSigner
public class PdfSigner
{
private String fileKey = null;
private String fileKeyPassword = null;
private String fileIn = null;
private String fileOut = null;
public PdfSigner() {}
public boolean signPdf() throws IOException, DocumentException, Exception
{
if (fileKey == null || fileKeyPassword == null || fileIn == null || fileOut == null) return false;
try
{
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(fileKey), fileKeyPassword.toCharArray());
String alias = (String) ks.aliases().nextElement();
PrivateKey key = (PrivateKey) ks.getKey(alias, fileKeyPassword.toCharArray());
Certificate[] chain = ks.getCertificateChain(alias);
//BOOOOOM!
PdfReader pdfReader = new PdfReader((new File(fileIn)).getAbsolutePath());
FileOutputStream outputFile = new FileOutputStream(fileOut);
PdfStamper pdfStamper = PdfStamper.createSignature(pdfReader, outputFile, '?');
PdfSignatureAppearance sap = pdfStamper.getSignatureAppearance();
sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
sap.setVisibleSignature(new Rectangle(10, 10, 50, 30), 1, "sign_rbl");
pdfStamper.close();
return true;
}
catch (Exception key)
{
throw new Exception(key);
}
}
//getters and setters
}
Well, this is wrong, but I don't know where does it fail. If I try to run it, it usually throw an exception in the line that I've marked with a "BOOOOM!", before setting the PdfReader. But if I try to sign it outside the procedure "factura", after closing the document, the exception is usually thrown almost in the last line, when I close the PdfStamper. In both cases, the cause is always the same: "PDF header signature not found."
Anyone has an idea of what's happening? I am 99% sure the paths I'm giving to the program are right, and the digital signature and password are also right...
Thanks
PS: I swear I've tried to find a solution among the multiple answers in this page, but none of them proved to be of any use to me

How does one save the .MoreInfo property of a PDF with iTextSharp?

I currently have the following class that I'm trying to add a Hashtable of metadata properties to a PDF. The problem is, even though it appears to assign the hashtable to the stamper.MoreInfo property it doesn't appear to save the MoreInfo property once the stamper is closed.
public class PdfEnricher
{
readonly IFileSystem fileSystem;
public PdfEnricher(IFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public void Enrich(string pdfFile, Hashtable fields)
{
if (!fileSystem.FileExists(pdfFile)) return;
var newFile = GetNewFileName(pdfFile);
var stamper = GetStamper(pdfFile, newFile);
SetFieldsAndClose(stamper, fields);
}
string GetNewFileName(string pdfFile)
{
return fileSystem.GetDirectoryName(pdfFile) + #"\NewFileName.pdf";
}
static void SetFieldsAndClose(PdfStamper stamper, Hashtable fields)
{
stamper.MoreInfo = fields;
stamper.FormFlattening = true;
stamper.Close();
}
static PdfStamper GetStamper(string pdfFile, string newFile)
{
var reader = new PdfReader(pdfFile);
return new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
}
}
Any ideas?
As always, Use The Source.
In this case, I saw a possibility fairly quickly (Java source btw):
public void close() throws DocumentException, IOException {
if (!hasSignature) {
stamper.close( moreInfo );
return;
}
Does this form already have signatures of some sort? Lets see when hasSignatures would be true.
That can't be the case with your source. hasSignatures is only set when you sign a PDF via PdfStamper.createSignature(...), so that's clearly not it.
Err... how are you checking that your MoreInfo was added? It won't be in the XMP metadata. MoreInfo is added directly to the Doc Info dictionary. You see them in the "Custom" tab of Acrobat (and most likely Reader, though I don't have it handy at the moment).
Are you absolutely sure MoreInfo isn't null, and all its values aren't null?
The Dictionary is just passed around by reference, so any changes (in another thread) would be reflected in the PDF as it was written.
The correct way to iterate through a document's "Doc info dictionary":
PdfReader reader = new PdfReader(somePath);
Map<String, String> info = reader.getInfo();
for (String key : info.keySet()) {
System.out.println( key + ": " + info.get(key) );
}
Note that this will go through all the fields in the document info dictionary, not just the custom ones. Also be aware that changes made the the Map from getInfo() will not carry over to the PDF. The map is new'ed, populated, and returned.