Unable to cast object of type 'Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.Model.Types.PdfLiteralString' to type 'Telerik.Windows.Documents.Fixed.FormatProviders.Pdf.Model.Types.PdfName'.

1 Answer 66 Views
General Discussions PdfProcessing SpreadProcessing SpreadStreamProcessing WordsProcessing ZipLibrary
Vaibhav
Top achievements
Rank 1
Iron
Iron
Vaibhav asked on 09 Dec 2024, 05:02 AM
the below method i got the exception i don't know what's wrong  can  anyone tell me 
the exception is occurred in below line 
  // Create PdfFormatProvider and load the existing document
 PdfFormatProvider pdfFormatProvider = new PdfFormatProvider();
 RadFixedDocument document = pdfFormatProvider.Import(inputStream);


static byte[] GenerateSignedPdf(Cert objCert, byte[] inDocByte)
{
    // Dimensions and positions for the signature field
    int signatureFieldWidth = 200; // Width of the signature field
    int signatureFieldHeight = 50;
    int signaturePositionLeft = 10;
    int signaturePositionTop = 10;

    // Load the certificate
    X509Certificate2 certificate = new X509Certificate2(objCert.CertArray, objCert.Password);

    // Create a SignatureField and assign the digital signature to it
    SignatureField pdfSignature = new SignatureField("SignatureField");
    pdfSignature.Signature = new Telerik.Windows.Documents.Fixed.Model.DigitalSignatures.Signature(certificate);

    // Set signature details
    string strNotAvailable = HttpContext.GetGlobalResourceObject("GlobalResources", "lblNotAvlbl").ToString();
    pdfSignature.Signature.Properties.Reason = strNotAvailable;
    pdfSignature.Signature.Properties.ContactInfo = strNotAvailable;
    pdfSignature.Signature.Properties.Location = strNotAvailable;

    // Load the existing PDF from the byte array using PdfFormatProvider
    using (MemoryStream inputStream = new MemoryStream(inDocByte))
    {
        // Create PdfFormatProvider and load the existing document
        PdfFormatProvider pdfFormatProvider = new PdfFormatProvider();
        RadFixedDocument document = pdfFormatProvider.Import(inputStream);

        // Create a new form to place the signature field
        Form pdfForm = new Form();
        pdfForm.FormSource = new FormSource();
        pdfForm.FormSource.Size = new Telerik.Documents.Primitives.Size(signatureFieldWidth, signatureFieldHeight);
        FixedContentEditor editor = new FixedContentEditor(pdfForm.FormSource);

        // Path to the image (ensure this is correct)
        var signatureImage = (System.Drawing.Image)HttpContext.Current.Session["imagesyncfusion"];

        // Drawing the image at the starting position (left side of the signature field)
        int imageWidth = signatureFieldWidth / 2;  // Half the width for the image
        int imageHeight = signatureFieldHeight;  // Use full height of the signature field

        // Create a memory stream to hold the image
        using (MemoryStream ms = new MemoryStream())
        {
            // Save the image to the memory stream
            signatureImage.Save(ms, signatureImage.RawFormat);

            // Reset the stream position to the beginning
            ms.Position = 0;

            // Pass the memory stream to the DrawImage method
            editor.DrawImage(ms, new Telerik.Documents.Primitives.Size(imageWidth, imageHeight));
        }

        string textToDraw = $"Digitally signed by {certificate.FriendlyName} \nDate: {DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss zzz")} \nReason: {pdfSignature.Signature.Properties.Reason} \nLocation: {pdfSignature.Signature.Properties.Location}";
        // Set the width of the text area (remaining space after the image)
        int textWidth = signatureFieldWidth - imageWidth;
        double dsd = CalculateFontSize(textWidth - 23, signatureFieldHeight, textToDraw);

        // Now, draw the text next to the image (on the right side), within the remaining space
        Telerik.Windows.Documents.Fixed.Model.Editing.Block textBlock = new Telerik.Windows.Documents.Fixed.Model.Editing.Block();
        int textPositionLeft = signaturePositionLeft + imageWidth;  // Adding a 5px gap after the image
        textBlock.TextProperties.FontSize = dsd;
        textBlock.InsertText($"Digitally signed by {certificate.FriendlyName}");
        textBlock.InsertText($" Date: {DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss zzz")}");
        textBlock.InsertText($" Reason: {pdfSignature.Signature.Properties.Reason}");
        textBlock.InsertText($" Location: {pdfSignature.Signature.Properties.Location}");
        Rect boundingRect = new Rect(textPositionLeft - 8, signaturePositionTop - 12, textWidth, signatureFieldHeight);
        textBlock.Draw(editor, boundingRect);

        // Create the SignatureWidget and position it on the PDF page
        SignatureWidget signatureWidget = pdfSignature.Widgets.AddWidget();
        signatureWidget.Content.NormalContentSource = pdfForm.FormSource;
        signatureWidget.Rect = new Rect(signaturePositionLeft, signaturePositionTop, signatureFieldWidth, signatureFieldHeight);
        signatureWidget.RecalculateContent();

        // Add content from the form to the page at the specified position
        RadFixedPage pdfPage = document.Pages[0];  // Assuming you're adding it to the first page
        FixedContentEditor pageEditor = new FixedContentEditor(pdfPage);
        pageEditor.Position.Translate(signaturePositionLeft, signaturePositionTop);
        pageEditor.DrawForm(pdfForm.FormSource);

        // Add the signature field to the document's AcroForm
        document.AcroForm.FormFields.Add(pdfSignature);

        // Use MemoryStream to capture the PDF output and return as a byte array
        using (MemoryStream memoryStream = new MemoryStream())
        {
            // Export the document to the memory stream as a PDF
            pdfFormatProvider.Export(document, memoryStream);
            return memoryStream.ToArray(); // Return the byte array of the signed PDF
        }
    }
}

1 Answer, 1 is accepted

Sort by
0
Dess | Tech Support Engineer, Principal
Telerik team
answered on 09 Dec 2024, 10:30 AM

Hello, Vaibhav,

Following the provided information and code snippet, I have prepared a sample project to test the behavior on my end. It was necessary to fine-tune the code in order to be buildable. Please refer to the attached zip file.

Considering the title of this ticket, I would like to share that we had a similar error reported previously and a fix was introduced in Q3 2024. Here is the feedback item for your reference: PdfProcessing: InvalidCastException when importing a PDF document with embedded files. In case you are using an older version, I would highly encourage you to upgrade in order to benefit from the fix.

If the error occurs when importing a specific PDF document only, it is possible to be related to the internal content of the precise document. It is hard for us to investigate the issues without actually having the problematic file. Please try and prepare a sample file without the sensitive information. If you decide you can also submit a private support ticket from your Telerik account and send us the original file. You can be certain that it will be used only for investigation purposes of this case and your privacy will be respected.  

I am sharing useful resources for the signing PDF documents functionality:

Signing a PDF Document with a SignatureWidget

Signing a document with a digital signature

How to Create Invisible Signatures for PDF Documents

Verifying If Digital Signatures Exist in PDF Documents

I hope this information helps. If you need any further assistance please don't hesitate to contact me. 

Regards,
Dess | Tech Support Engineer, Principal
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Vaibhav
Top achievements
Rank 1
Iron
Iron
commented on 09 Dec 2024, 12:13 PM

Hi, Dess
this issue has been produced one of my pdf don't know why ?
Dess | Tech Support Engineer, Principal
Telerik team
commented on 11 Dec 2024, 12:48 PM

Hi, Vaibhav,

If the issue is reproducible only with a specific PDF document, it would greatly appreciated if you can provide that file. In case you are worried about confidentiality, I would encourage you to submit a private support ticket from your Telerik account. Thus, we would be able to make an adequate analysis of the precise case and provide further assistance. Thank you in advance for your cooperation.

Vaibhav
Top achievements
Rank 1
Iron
Iron
commented on 12 Dec 2024, 09:02 AM

Hi, Dess 
i am not able to provide the pdf can you suggest me how i can provide the pdf to you, because here only specific type of file i can share mine is pdf so i was not able to upload the pdf
Dess | Tech Support Engineer, Principal
Telerik team
commented on 12 Dec 2024, 02:50 PM

Hi, Vaibhav,

I suppose that you are observing the following message when uploading directly the PDF document:

However, if you zip the PDF document, it is expected to be properly uploaded:

You can give this approach a try.

Please do not forget that this is a public forum post and if you have any confidential data in the PDF document, an alternative approach is to submit a private support ticket.

Vaibhav
Top achievements
Rank 1
Iron
Iron
commented on 13 Dec 2024, 03:54 AM

Hi, Dess
Thank you find that pdf and let me know what's wrong why i am getting that exception
Dess | Tech Support Engineer, Principal
Telerik team
commented on 16 Dec 2024, 10:19 AM

Hi, Vaibhav,

Thank you for providing the sample PDF document. I was able to replicate the InvalidCastException simply by importing the document when the Arial,Italic font is read. 

I have logged it in our feedback portal by creating a public thread on your behalf. You can cast your vote for the item, track its progress, subscribe for status changes, and add your comments on the following link: PdfProcessing: InvalidCastException when parsing the font for a specific document.

I have also updated your Telerik points.

Currently, due to the specificity of the issue, I am unable to suggest an appropriate solution. Please excuse us for the inconvenience caused. We will do our best to introduce a proper fix accordingly.

Tags
General Discussions PdfProcessing SpreadProcessing SpreadStreamProcessing WordsProcessing ZipLibrary
Asked by
Vaibhav
Top achievements
Rank 1
Iron
Iron
Answers by
Dess | Tech Support Engineer, Principal
Telerik team
Share this question
or