0

I'm working on an application which receives a PDF file with content(data) from another system for customer to do the digital signature. My task is to add customer details and timeStamp after signing without losing current data or without creating a new pdf file. (DateTime, name, surname, etc).

I have followed a few examples(see below) on the test app and it works fine.

How to update a PDF without creating a new PDF?

ITextSharp insert text to an existing pdf

The problem is that it is looking for a new file which is not what I want.

How can I amend/add text to an existing pdf file without creating a new pdf? I am a little bit lost on how I can archive this after searching for two days

file is encoded

var file = new PDFFile();
------
------
file.OriginalFileData = Convert.FromBase64String(model.FileData);

//Model
public string FileData { get; set; }

PDF File entity

public class PDFFile
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
    public int Id { get; set; }

    public string FileName { get; set; }
    public string Description { get; set; }

    public DateTime DateCreated { get; set; }
    public string OriginatingSystem { get; set; }
    public string OriginatorName { get; set; }

    public string FileLocator { get; set; }

    public DateTime? ExpiryDate { get; set; }

    public Customer Customer { get; set; }
    [InverseProperty("AssignedDocuments")]
    public ApplicationUser User { get; set; }

    public int NumPages { get; set; }

    public DocumentState State { get; set; }

    [InverseProperty("ActionedDocuments")]
    public ApplicationUser ActionedUser { get; set; }
    public DateTime? ActionDate { get; set; }

    public byte[] OriginalFileData { get; set; }
    public byte[] EditedFileData { get; set; }
    public byte[] SignedFileData { get; set; }
    public virtual ICollection<PDFFileMetaData> Metadata { get; set; }

 }

 //PDFFileMetaData
public class PDFFileMetaData
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
    public int Id { get; set; }

    [InverseProperty("Metadata")]
    public PDFFile Document { get; set; }
    public string Key { get; set; }
    public string Data { get; set; }
}

My code:

    public SoapResponse SignCustomerDocument(Customer customer, PDFFile document, ApplicationUser user)
    {

        var logger = log4net.LogManager.GetLogger(this.GetType());

        string timePoint = DateTime.Now.ToString("yyyyMMdd'T'HHmmss'.'fffffff");

        string transactionId = "SP_" + timePoint + ".D" + document.Id + ".C" + customer.Id;
        logger.InfoFormat("Sending signing request {0}", transactionId);

        var signReq = new PdfSigningRequest();
        signReq.Echo = transactionId;
        signReq.TransactionId = transactionId;
        if (signReq.Document == null)
            signReq.Document = new PdfSigningDocument();

        byte[] fileData = PDFEditorHelper.EditPdf(document, document.OriginalFileData, user.InitialImage);
        byte[] editedPDF = this.EditSignablePDF(document, fileData);

        signReq.Document.FileBytes = editedPDF;
        signReq.Document.Identifier = transactionId;
        if (signReq.Document.PdfSigningParameters == null)
            signReq.Document.PdfSigningParameters = new PdfSigningParameters();


        //variables
        int numberOfPages;

        //create PdfReader object to read from the existing document
        using (PdfReader reader = new PdfReader(document.OriginalFileData))

        //create PdfStamper object to write to get the pages from reader 
        using (PdfStamper stamper = new PdfStamper(reader, new FileStream(Convert.ToString(document.EditedFileData), FileMode.Create)))
        {
            numberOfPages = reader.NumberOfPages;
            //select two pages from the original document
            reader.SelectPages("1-100");


            //gettins the page size in order to substract from the iTextSharp coordinates
            var pageSize = reader.GetPageSize(1);

            // PdfContentByte from stamper to add content to the pages over the original content
            PdfContentByte pbover = stamper.GetOverContent(18);

            //add content to the page using ColumnText
            iTextSharp.text.Font font = new iTextSharp.text.Font();
            font.Size = 12;


            //setting up the X and Y coordinates of the document

            System.Drawing.Point point = new Point();
            int x = point.X;
            int y = point.Y;

            y = (int)(pageSize.Height - y);


            string FisrtName = "Test1";
            string Position = "Test2";
            string Signature = "Test3";
            string SignatureDate = DateTime.Now.ToString();

            ColumnText.ShowTextAligned(pbover, Element.ALIGN_UNDEFINED, new Phrase(FisrtName, font), 230, 650, 0);
            ColumnText.ShowTextAligned(pbover, Element.ALIGN_JUSTIFIED, new Phrase(Position, font), 230, 628, 0);
            ColumnText.ShowTextAligned(pbover, PdfContentByte.ALIGN_LEFT, new Phrase(Signature, font), 230, 600, 0);
            ColumnText.ShowTextAligned(pbover, PdfContentByte.ALIGN_LEFT, new Phrase(SignatureDate, font), 230, 574, 0);

        }
  }

The error I get on the above code:

enter image description here

IT Forward
  • 367
  • 2
  • 7
  • 28
  • 1
    There's a lot going on in that example, which is probably putting people off from answering. There doesn't appear to be any code for saving the edited file (which is what you're asking about) and the error doesn't look as if it's related to saving - it's all very confusing and hard to answer. – Robin Bennett May 14 '20 at 07:55
  • @RobinBennett It is not about saving, but writing on existing PDF. Every time when I try to add text I get that error. I was trying to give more context to what I want. I cannot save it before adding those texts. – IT Forward May 14 '20 at 08:11
  • Have you tried debugging your code and checked whether one of the variables used on that code line is unexpectedly `null`? For example, if the originally read PDF has less than 18 pages, `pbover` is `null`... – mkl May 14 '20 at 16:50
  • @mkl let me try yo debug and see where it is being sent to null and I will revert back to you. – IT Forward May 14 '20 at 17:44
  • I have dive deep and investigate why it is setting to null. I figured out that "pbover" was being null. I have now since added number of pages and it is not setting the values to null. PdfContentByte pbover = stamper.GetOverContent(numberOfPages); Now it is not showing newly added text. It is blank. I am not sure what's the problem – IT Forward May 14 '20 at 18:04

0 Answers0