Telerik Forums
Telerik Document Processing Forum
1 answer
664 views

After upgrading the Telerik Document Processing libraries to version Q1 2025 the following error messages may occur:

* "The file or assembly cannot be loaded 'Telerik.Licensing.Runtime, Version=1.4.6.0, Culture=neutral, PublicKeyToken=token_here' or one of its dependencies. The system cannot find the specified file."

* "NU1101: Unable to find package Telerik.Licensing. No packages exist with this id in source(s): Telerik nuget. PackageSourceMapping is enabled, the following source(s) were not considered: Microsoft Visual Studio Offline Packages, nuget.org."

Dess | Tech Support Engineer, Principal
Telerik team
 answered on 12 Feb 2025
1 answer
150 views
Is Telerik's NuGet server currently down or experiencing any issues? I'm unable to install packages from the Telerik feed, and I want to confirm if it's a known outage.
Dess | Tech Support Engineer, Principal
Telerik team
 answered on 25 Nov 2024
1 answer
52 views

The contents of an uploaded .docx file is being cut-off when converted to .pdf file.

 

Code snippet:

var fileFormatProvider = new Telerik.Windows.Documents.Flow.FormatProviders.Docx.DocxFormatProvider(); using (MemoryStream inputFileStream = new MemoryStream()) { this.fileSystemService.GetFile(documentInfo, inputFileStream); if (fileFormatProvider != null) { var document = fileFormatProvider.Import(inputFileStream); using (MemoryStream output = new MemoryStream()) { var pdfProvider = new Telerik.Windows.Documents.Flow.FormatProviders.Pdf.PdfFormatProvider(); pdfProvider.Export(document, output); var newFile = new DocumentInfo() { NameWithPath = outputFileName, DocumentLocation = documentInfo.DocumentLocation }; this.fileSystemService.SaveFile(newFile, output); } }

 

Can someone confirm if this a Telerik side issue, or am I missing a setting or config?

 

Thanks!

Dess | Tech Support Engineer, Principal
Telerik team
 answered on 26 Feb 2025
0 answers
38 views

Can someone help me figure out what is wrong here?  I'm getting ad horribly vague Null exception.

 

var docxProvider = new Telerik.Windows.Documents.Flow.FormatProviders.Docx.DocxFormatProvider();
var pdfProvider = new Telerik.Windows.Documents.Flow.FormatProviders.Pdf.PdfFormatProvider();
RadFlowDocument document = new RadFlowDocument();
byte[] docBytes = File.ReadAllBytes(path);

document = docxProvider.Import(docBytes);    ERROR HERE

var resultBytes = pdfProvider.Export(document);

File.WriteAllBytes(resultPath, resultBytes);

 

The document i'm trying to load contains tables and images within the tables (jpeg barcodes)

I have verified that pretty much every other tool i use can read the file without issue. 

The goal is ultimately to export the file as a PDF.

 

Error details:

{"Object reference not set to an instance of an object."}

   at Telerik.Windows.Documents.Flow.FormatProviders.Docx.Model.Elements.Document.ParagraphPropertiesElement.OnAfterRead(IDocxImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase`3.OnAfterRead(IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.Read(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.ReadChildElements(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.Read(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.ReadChildElements(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.Read(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.ReadChildElements(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.Read(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.ReadChildElements(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.Read(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.ReadChildElements(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Elements.OpenXmlElementBase.Read(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Parts.OpenXmlPartBase.Import(IOpenXmlReader reader, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.Model.Parts.OpenXmlPartBase.Import(Stream stream, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.OpenXmlImporter`1.ImportPartFromArchive(ZipArchiveEntry zipEntry, PartBase part, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.FormatProviders.OpenXml.OpenXmlImporter`1.Import(Stream input, IOpenXmlImportContext context)
   at Telerik.Windows.Documents.Flow.FormatProviders.Docx.DocxFormatProvider.ImportOverride(Stream input)
   at Telerik.Windows.Documents.Common.FormatProviders.FormatProviderBase`1.Import(Stream input)
   at Telerik.Windows.Documents.Common.FormatProviders.BinaryFormatProviderBase`1.Import(Byte[] input)
   at IVC_BIPS_Desktop.rfrmMain.ConverDocxToPdf(String path, String resultPath) in C:\Source\IVC Batch Instructions Printing\IVC_BIPS_Desktop\rfrmMain.cs:line 499
Jamie
Top achievements
Rank 1
 asked on 20 Feb 2025
0 answers
65 views
Hi,

i have added and image and some text inside the digital signature and and set them inside properly but when i set the position of the signature field before the signature field like i was showing in below screenshot 


above screenshot i have added the signature field placed the top of the Letter M but when i validate the signature manually but in output the signature field position is not correct as i set the above screenshot below is the screenshot that you can check the position of the signature field

i don't know whats strange can anyone help me this to get it out  
0 answers
203 views
i am getting the Telerik.Windows.Documents.Fixed.Exceptions.NotSupportedImageFormatException: 'Not supported image format.'  this exception in below code can anyone have a solution for that 


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

    int pageNo = (signInfo.DigitalSignPage() == 0 ? 1 : document.Pages.Count);

    // Path to the image (ensure this is correct)
    System.Drawing.Image signatureImage = null;
    if (signInfo.DigitalSignMode() == 2 && HttpContext.Current.Session["imagesyncfusion"] != null)
    {
        signatureImage = (System.Drawing.Image)HttpContext.Current.Session["imagesyncfusion"];
    }
    // Check if digital signature is needed
    if (signInfo.UseDigitalSign())
    {
        if ((signInfo.DigitalSignMode() == 1) || (signInfo.DigitalSignMode() == 2))
        {
            double signaturePositionLeft = (double)signInfo.DigitalSignLeftInPoints();
            double signaturePositionTop = (double)signInfo.DigitalSignTopInPoints();
            double signatureFieldWidth = (double)signInfo.DigitalSignWidthInPoints();
            double signatureFieldHeight = (double)signInfo.DigitalSignHeightInPoints();
            RadFixedPage radFixedPage = document.Pages[pageNo - 1];

            if (!string.IsNullOrEmpty(customSignatureDetails))
            {
                // Movable signature case: Adjust the signature field based on custom details
                signatureFieldWidth = signaturePositionLeft + (double)signInfo.DigitalSignWidthInPoints();
                signatureFieldHeight = signaturePositionTop + (double)signInfo.DigitalSignHeightInPoints();

                string[] separator = new string[] { "!_!" };
                string[] offsetArray = customSignatureDetails.Split(separator, StringSplitOptions.RemoveEmptyEntries);

                if (offsetArray.Length >= 9)
                {
                    float offsetLeft = returnFloatWithCultureValue(offsetArray[0]);
                    float offsetTop = returnFloatWithCultureValue(offsetArray[1]);
                    float docHeight = returnFloatWithCultureValue(offsetArray[2]);
                    float greenDivHeight = returnFloatWithCultureValue(offsetArray[3]);
                    float greenDivWidth = returnFloatWithCultureValue(offsetArray[4]);
                    float dpi_x = returnFloatWithCultureValue(offsetArray[6]);
                    float dpi_y = returnFloatWithCultureValue(offsetArray[7]);
                    pageNo = int.Parse(offsetArray[8]);

                    // Calculate positions for drawing the text div;
                    signaturePositionLeft = (offsetLeft / dpi_x) * 72;
                    signaturePositionTop = (offsetTop / dpi_y) * 72;
                    signatureFieldWidth = (greenDivWidth / dpi_y) * 72;
                    signatureFieldHeight = (greenDivHeight / dpi_x) * 72;
                }
            }
            else
            {
                // Non-movable case: Place the signature field in a fixed location
                radFixedPage = document.Pages[pageNo - 1];
                Tuple<double, double> k = null;

                if (signatureImage != null)
                {
                    k = calculateAspectRatioFit(signatureImage.Width, signatureImage.Height, signatureFieldWidth, signatureFieldHeight);
                    signatureFieldWidth = k.Item1;
                    signatureFieldHeight = k.Item2;
                }

                signaturePositionLeft = radFixedPage.Size.Height - (double)(signatureFieldWidth + signatureFieldHeight + 1);
                signaturePositionTop = signaturePositionTop + 1; // +1 For border size
                                                                 //pdfForm.FormSource.Size = new Telerik.Documents.Primitives.Size(signatureFieldWidth, signatureFieldHeight);
            }

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

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

            if (signatureImage != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    signatureImage.Save(ms, signatureImage.RawFormat);
                    ms.Position = 0;
                    editor.DrawImage(ms, new Telerik.Documents.Primitives.Size(imageWidth, imageHeight));
                }
            }

            // Prepare text to draw beside the signature image
            string textToDraw = $"Digitally signed by {certificate.FriendlyName} \nDate: {DateTime.Now:yyyy.MM.dd HH:mm:ss zzz} \nReason: {pdfSignature.Signature.Properties.Reason} \nLocation: {pdfSignature.Signature.Properties.Location}";

            // Set text width and calculate font size
            double textWidth = signatureFieldWidth - imageWidth;
            double fontSize = CalculateFontSize(signatureFieldWidth - 23, signatureFieldHeight, textToDraw);

            // Define the position for the text and draw it
            Telerik.Windows.Documents.Fixed.Model.Editing.Block textBlock = new Telerik.Windows.Documents.Fixed.Model.Editing.Block();
            double textPositionLeft = signaturePositionLeft;  // Adding a 5px gap after the image
            textBlock.TextProperties.FontSize = fontSize;
            textBlock.InsertText($"Digitally signed by {certificate.FriendlyName}");
            textBlock.InsertText($" Date: {DateTime.Now:yyyy.MM.dd HH:mm:ss zzz}");
            textBlock.InsertText($" Reason: {pdfSignature.Signature.Properties.Reason}");
            textBlock.InsertText($" Location: {pdfSignature.Signature.Properties.Location}");
            
            Rect boundingRect;
            if (signatureImage != null)
            {
                boundingRect = new Rect(imageWidth, 5, textWidth, signatureFieldHeight);
            }
            else
            {
                boundingRect = new Rect(textPositionLeft, 5, textWidth, signatureFieldHeight);
            }
            textBlock.Draw(editor, boundingRect);
            //editor.DrawBlock(textBlock);
            // 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, 0, signatureFieldWidth, signatureFieldHeight);
            signatureWidget.RecalculateContent();

            // Add signature widget to the page and draw the content
            RadFixedPage pdfPage = document.Pages[pageNo - 1];
            FixedContentEditor pageEditor = new FixedContentEditor(pdfPage);
            pageEditor.Position.Translate(signaturePositionLeft , signaturePositionTop + 258.3824795800782);
            pageEditor.DrawForm(pdfForm.FormSource);

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

        }

    }
    // Export the document to a byte array and return
    using (MemoryStream memoryStream = new MemoryStream())
    {

        Telerik.Documents.ImageUtils.ImagePropertiesResolver defaultImagePropertiesResolver = new Telerik.Documents.ImageUtils.ImagePropertiesResolver();
        Telerik.Windows.Documents.Extensibility.FixedExtensibilityManager.ImagePropertiesResolver = defaultImagePropertiesResolver;
        PdfExportSettings settings = new PdfExportSettings() { ImageQuality = ImageQuality.High };
        //PdfFormatProvider provider = new PdfFormatProvider();
        provider.ExportSettings = settings;
        provider.Export(document, memoryStream);
        outDocPdf = memoryStream.ToArray();
    }
0 answers
62 views
public static void SignPDFSynfusion(SignatureInfo signInfo, byte[] inDocByte, Cert objCert, string customSignatureDetails, out byte[] outDocPdf)
{
    // Dimensions and positions for the signature field
    double signatureFieldWidth; // Width of the signature field
    double signatureFieldHeight;
    double signaturePositionLeft;
    double signaturePositionTop;
   
    // Getting TimeStamp Details from Database..
    TimeStampSettings objTimeStampSettings = new TimeStampSettings();
    TimeStampInfo objTimeStampInfo = (TimeStampInfo)objTimeStampSettings.GetTimeStamp();
    PfxSettings objPfxSettings = new PfxSettings();

    // Params to take account in the input
    bool displaySignature = Convert.ToBoolean(HttpContext.Current.Session["showSign"]);

    bool needTimeStamp = false;
    string TsaServerUrl = "";
    string TsaServerUser = "";
    string TsaServerPassword = "";
    string strPasswrd = string.Empty;
    double imageWidth = 0;

    if (objTimeStampInfo != null)
    {
        needTimeStamp = (bool)objTimeStampInfo.TimeStampNeeded;
        TsaServerUrl = objTimeStampInfo.TimeStampUrl;

        if ((bool)objTimeStampInfo.AuthNeeded)
        {
            TsaServerUser = objTimeStampInfo.UserName;
            strPasswrd = SecurQueryString.decryptQueryString(objTimeStampInfo.Password);
            TsaServerPassword = strPasswrd;
        }
    }
    // 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;

    // Create a new form to place the signature field
    Form pdfForm = new Form();
    pdfForm.FormSource = new FormSource();

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

        int pageNo = (signInfo.DigitalSignPage() == 0 ? 1 : document.Pages.Count);
        try
        {
            if (needTimeStamp)
            {
                //.TimeStampServer = new TimeStampServer(new Uri(TsaServerUrl), TsaServerUser, TsaServerPassword);
            }
        }
        catch (Exception ex)
        { }

        // Path to the image (ensure this is correct)
        System.Drawing.Image signatureImage = null;
        if (signInfo.DigitalSignMode() == 2 && HttpContext.Current.Session["imagesyncfusion"] != null)
        {
            signatureImage = (System.Drawing.Image)HttpContext.Current.Session["imagesyncfusion"];
        }
        //var signatureImage = (System.Drawing.Image)HttpContext.Current.Session["imagesyncfusion"];

        if (signInfo.UseDigitalSign())
        {
            if ((signInfo.DigitalSignMode() == 1) || (signInfo.DigitalSignMode() == 2))
            {
                signaturePositionLeft = (double)signInfo.DigitalSignLeftInPoints();
                signaturePositionTop = (double)signInfo.DigitalSignTopInPoints();
                signatureFieldWidth = (double)signInfo.DigitalSignWidthInPoints();
                signatureFieldHeight = (double)signInfo.DigitalSignHeightInPoints();
                RadFixedPage radFixedPage = document.Pages[pageNo - 1];
                if (!string.IsNullOrEmpty(customSignatureDetails))
                {
                    //Movable case:
                    signatureFieldWidth = signaturePositionLeft + (double)signInfo.DigitalSignWidthInPoints();
                    signatureFieldHeight = signaturePositionTop + (double)signInfo.DigitalSignHeightInPoints();

                    string[] separator = new string[] { "!_!" };
                    string[] offsetArray = customSignatureDetails.Split(separator, StringSplitOptions.RemoveEmptyEntries);

                    if (offsetArray.Length >= 9)
                    {
                        float offsetLeft = returnFloatWithCultureValue(offsetArray[0]);
                        float offsetTop = returnFloatWithCultureValue(offsetArray[1]);
                        float docHeight = returnFloatWithCultureValue(offsetArray[2]);
                        float greenDivHeight = returnFloatWithCultureValue(offsetArray[3]);
                        float greenDivWidth = returnFloatWithCultureValue(offsetArray[4]);
                        float dpi_x = returnFloatWithCultureValue(offsetArray[6]);
                        float dpi_y = returnFloatWithCultureValue(offsetArray[7]);
                        pageNo = int.Parse(offsetArray[8]);

                        // Calculate positions for drawing the text div;
                        signaturePositionLeft = (offsetLeft / dpi_x) * 72;
                        signaturePositionTop = (offsetTop / dpi_y) * 72;
                        signatureFieldWidth = (greenDivWidth / dpi_y) * 72;
                        signatureFieldHeight = (greenDivHeight / dpi_x) * 72;

                        pdfForm.FormSource.Size = new Telerik.Documents.Primitives.Size(signatureFieldWidth, signatureFieldHeight);

                    }
                }
                else
                {
                    //Non-movable case:
                    radFixedPage = document.Pages[pageNo - 1];
                    Tuple<double, double> k = null;

                    if (signatureImage != null)
                    {
                        k = calculateAspectRatioFit(signatureImage.Width, signatureImage.Height, signatureFieldWidth, signatureFieldHeight);
                        signatureFieldWidth = k.Item1;
                        signatureFieldHeight = k.Item2;
                    }

                    signaturePositionLeft = radFixedPage.Size.Height - (double)(signatureFieldWidth + signatureFieldHeight + 1);
                    signaturePositionTop = signaturePositionTop + 1; // +1 For border size
                    pdfForm.FormSource.Size = new Telerik.Documents.Primitives.Size(signatureFieldWidth, signatureFieldHeight);
                }
                FixedContentEditor editor = new FixedContentEditor(pdfForm.FormSource);
                // Drawing the image at the starting position (left side of the signature field)
                imageWidth = signatureFieldWidth / 2;  // Half the width for the image
                double imageHeight = signatureFieldHeight;  // Use full height of the signature field

                if (signatureImage == null)
                {

                }
                else
                {
                    // 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)
                double textWidth = signatureFieldWidth - imageWidth;
                double dsd = CalculateFontSize(textWidth, 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();
                double textPositionLeft = signaturePositionLeft + imageWidth;  // Adding a 5px gap after the image
                textBlock.TextProperties.FontSize = 8;
                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
            Telerik.Documents.ImageUtils.ImagePropertiesResolver defaultImagePropertiesResolver = new Telerik.Documents.ImageUtils.ImagePropertiesResolver();
            Telerik.Windows.Documents.Extensibility.FixedExtensibilityManager.ImagePropertiesResolver = defaultImagePropertiesResolver;
            var settings = new PdfExportSettings();
            settings.ImageQuality = ImageQuality.High;
            provider.ExportSettings = settings;
            provider.Export(document, memoryStream);
            // Return the byte array of the PDF
            outDocPdf = memoryStream.ToArray();
            //return memoryStream.ToArray(); // Return the byte array of the signed PDF
        }
    }
}
       private static double CalculateFontSize(double textWidth, double signatureFieldHeight, string text)
       {
           // Start with a base font size for better precision
           double baseFontSize = 12.0;  // Starting font size

           // Calculate width scale factor to adjust the font size based on text length
           double widthScaleFactor = textWidth / text.Length;
           double widthFontSize = baseFontSize * widthScaleFactor;

           // Calculate height scale factor to adjust the font size based on the number of lines
           int numLines = text.Split('\n').Length;
           double heightScaleFactor = signatureFieldHeight / (numLines * baseFontSize);
           double heightFontSize = baseFontSize * heightScaleFactor;

           // Return the smaller font size to fit both dimensions
           return Math.Min(widthFontSize, heightFontSize);
       }

       public static Tuple<double, double> calculateAspectRatioFit(double srcWidth, double srcHeight, double maxWidth, double maxHeight)
       {
           var ratio = Math.Min(maxWidth / srcWidth, maxHeight / srcHeight);
           return new Tuple<double, double>(srcWidth * ratio, srcHeight * ratio);
       }
1 answer
75 views

firstly loading the document i have use 
  // Load the PDF document
  var provider = new PdfFormatProvider();
  var loadedDocument = provider.Import(inDocByte,null);

and after some functinality to export the document i have used below 

 Telerik.Documents.ImageUtils.ImagePropertiesResolver defaultImagePropertiesResolver = new Telerik.Documents.ImageUtils.ImagePropertiesResolver();
 Telerik.Windows.Documents.Extensibility.FixedExtensibilityManager.ImagePropertiesResolver = defaultImagePropertiesResolver;
 provider.Export(document, memoryStream, null);
 outDocPdf = memoryStream.ToArray();

what was the problem can you tell me the solution for that exception

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'.

Dess | Tech Support Engineer, Principal
Telerik team
 answered on 09 Dec 2024
1 answer
103 views
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
        }
    }
}
Dess | Tech Support Engineer, Principal
Telerik team
 answered on 09 Dec 2024
1 answer
47 views

Hi,

1) i want to add and image and text in the signature field with specified size and i want to do that in the existing pdf with signature field ?
2) how to add any type of image [jpg, jpeg , png, etc.] in extsting pdf 
 static byte[] GenerateSignedPdf(Cert objCert)
 {
     // Dimensions and positions for the signature field
     int signatureFieldWidth = 200;
     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);

     // 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);

     // Draw the text with certificate holder's name and current date
     string textToDraw = $"{certificate.GetNameInfo(X509NameType.SimpleName, false)} {DateTime.Now:yyyy.MM.dd HH:mm}";
     editor.DrawText(textToDraw, new Telerik.Documents.Primitives.Size(5, 5)); // Adjust position as needed

     // Path to the image (ensure this is correct)
     string imagePath = "C:/Vaibhav/ProjectVaibhav/PdfProcessing_InsertImageInExistingPdf/image.png"; // Change path as needed

     // Ensure the image exists and can be accessed
     if (File.Exists(imagePath))
     {
         using (var imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
         {
             var imageSource = new ImageSource(imageStream);
             editor.DrawImage(imageSource, new Telerik.Documents.Primitives.Size(100, 50)); // Adjust image size and position as needed
         }
     }
     else
     {
         throw new FileNotFoundException("Image file not found at: " + imagePath);
     }

     // 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();

     // Create a RadFixedDocument and add a page
     RadFixedDocument document = new RadFixedDocument();
     RadFixedPage pdfPage = document.Pages.AddPage();
     pdfPage.Annotations.Add(signatureWidget);

     // Add content from the form to the page at the specified position
     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())
     {
         var pdfFormatProvider = new PdfFormatProvider();
         pdfFormatProvider.Export(document, memoryStream);
         return memoryStream.ToArray(); // Return the byte array of the PDF
     }
 }

Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?