Question

I am currently working on a process that will use iTextSharp to partially fill a PDF form. This form is then emailed to a user and the user will finish completing the form. Then the form is submitted by email back to our email account and then processed.

My problem is that once the PDF is sent out to a user, when the user opens the form and the data can not be saved. The original PDF that is used as a template can be filled out an saved. Somehow, during the process of using iTextSharp, the form is losing its usage rights. Is there a way to retain the usage rights while using iTextSharp?

I am hoping that someone here can point out what is going wrong, or point me in the right direction. Thanks for your time and help.

Below is the code:

using Dapper;
using iTextSharp.text.pdf;
using NLog;
using PilotDispatch.Domain.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OleDb;
using System.IO;
using System.Linq;

namespace eTicketPdfFactory
{
    class Program
    {
        const string TemplateItextPdfPath = @"C:\PDF\Factory\eTicketFormPortrait.pdf";
        const string OutputItextPdfPath = @"C:\PDF\Factory\eTicketFormPortraitOut.pdf";


    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        static void Main(string[] args)
        {
            var logid = string.Empty;
            if (args.Length > 0)
            {
                logid = args[0];
            }
            else
            {
                Logger.Error("No LogId supplied");
                return;
            }

            var rundownQuery =
                string.Format(
                    "SELECT * FROM Rundown_Table LEFT JOIN Vessels ON Vessels.CallSign = Rundown_Table.Call_Sign WHERE Rundown_Table.Log_ID = '{0}'",
                    logid);


            ETicketPdf ticket;
            IEnumerable<PilotTransportation> pilotTransportations = null;

            using (var cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["PervasiveConnection"].ConnectionString))
            {
                cn.Open();
               // ticket = cn.Query<ETicketPdf>(PervasiveQueryString, new { Log_ID = logid }).FirstOrDefault(); // not working with Pervasive
                ticket = cn.Query<ETicketPdf>(rundownQuery).FirstOrDefault();

                if (ticket != null)
                {
                    var transportationQuery =
                        string.Format(
                            "SELECT * FROM PilotTransportation WHERE PilotCode = '{0}'",
                            ticket.Pilot_Code);

                    pilotTransportations = cn.Query<PilotTransportation>(transportationQuery);
                }

                cn.Close();
            }

            if (ticket == null)
            {
                Logger.Error("No records found for given LogId");
                return;
            }

           var pilotOptions = pilotTransportations.Select(opt => string.Format("{0} - {1}", opt.VendorID, opt.Name)).ToArray();


            var reader = new PdfReader(TemplateItextPdfPath);
            var stamper = new PdfStamper(reader, new FileStream(OutputItextPdfPath, FileMode.Open));
            //var stamper = new PdfStamper(reader, new FileStream(OutputItextPdfPath, FileMode.CreateNew, FileAccess.Write), '\0', true);
            var formFields = stamper.AcroFields;

            formFields.SetListOption("Form[0].Page1[0].VendorIdFrom1[0]", null, pilotOptions);
            formFields.SetListOption("Form[0].Page1[0].VendorIdTo1[0]", null, pilotOptions);
            formFields.SetListOption("Form[0].Page1[0].VendorIdFrom2[0]", null, pilotOptions);
            formFields.SetListOption("Form[0].Page1[0].VendorIdTo2[0]", null, pilotOptions);

            var properties = ticket.GetType().GetProperties();

            foreach (var prop in properties)
            {
                var name = prop.Name;
                var propval = prop.GetValue(ticket, null);

                if (propval != null)
                {
                    if (name == "Order_Date")
                    {
                        if(Convert.ToDateTime(propval).Year < 1902)continue;
                    }

                    formFields.SetField(name, propval.ToString());
                }

            }

            reader.RemoveUsageRights();
            stamper.Close();
            reader.Close();

            File.Copy(OutputItextPdfPath, Path.GetDirectoryName(OutputItextPdfPath) + "/" + logid + ".pdf");

            Console.WriteLine("finished");
            Console.ReadLine();
        }
    }
}

Once again, thanks in advance for any pointers or help that you can offer me.

Was it helpful?

Solution

The answer is commented out in your own source code.

You need:

var stamper = new PdfStamper(reader, new FileStream(...), '\0', true);

instead of:

var stamper = new PdfStamper(reader, new FileStream(...));

Your question is a duplicate of How to correctly fill in XFA form data using iTextSharp to allow editing and saving result in Acrobat XI and you can find a more elaborate answer here.

Also: you complain that the usage rights are removed, but if that is so, why do I see this line in your code:

reader.RemoveUsageRights();

That line removes the usage rights and therfore the form can no longer be saved locally when using Adobe Reader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top