Telerik Forums
Telerik Document Processing Forum
0 answers
15 views

After recent update to 2025.2.520.462 I'm unable to extract file and save on disk. ExtractToFile() method is not longer here.
I've changed my usings from Telerik.WinControls.Zip to Telerik.Windows.Zip but I'm missing Telerik.Windows.Zip.Extensions.dll file.

What should I replace method ExtractToFile() with?

There is a code we use right now:

 

Byte[] bytes = File.ReadAllBytes(filePath);
using (MemoryStream zipStream = new MemoryStream(bytes))
using (ZipArchive archive = ZipArchive.Read(zipStream))
{
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        string extractedFilePath = Path.Combine(Path.GetTempPath(), entry.FullName);
        entry.ExtractToFile(extractedFilePath, true);
        thumbnail = AddGridFile(extractedFilePath);
        File.Delete(extractedFilePath);
    }
}
Pruszkow
Top achievements
Rank 1
 updated question on 22 May 2025
0 answers
68 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
213 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
66 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
76 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
106 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
51 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
     }
 }

1 answer
157 views
System.InvalidOperationException: 'FixedExtensibilityManager.ImagePropertiesResolver and FixedExtensibilityManager.JpegImageConverter cannot be both null. The .NET Standard does not define APIs for decoding images. That`s why in order to export images different than Jpeg and Jpeg2000 and ImageQuality different than High you will need to reference the Telerik.Documents.ImageUtils assembly/NuGet in your project and to set its basic implementation to the ImagePropertiesResolver/JpegImageConverter property or to create a custom one inheriting the ImagePropertiesResolverBase/JpegImageConverterBase class. For more information go to: https://docs.telerik.com/devtools/document-processing/libraries/radpdfprocessing/cross-platform/images'
Dess | Tech Support Engineer, Principal
Telerik team
 answered on 28 Nov 2024
0 answers
541 views
     public void UnzipTSWFiles(string sourceDirectory, string destinationDirectory, string password)
        {
            DefaultEncryptionSettings protectionSettings = new DefaultEncryptionSettings() { Password = password };

                 using (ZipArchive zipArchive = new ZipArchive(output, ZipArchiveMode.Read, true, null, null, protectionSettings))
                        {
                            foreach (ZipArchiveEntry entry in zipArchive.Entries)
                            {
                                using (Stream entryStream = entry.Open())
                                using (FileStream fileStream = File.OpenWrite(string.Format("{0}/{1}", targetDirectory, entry.FullName)))
                                {
                                    entryStream.CopyTo(fileStream);
                                }
                            }
                        }
                    
         

        }
purushotham
Top achievements
Rank 1
 asked on 09 Aug 2023
1 answer
785 views

Good morning,

I have a process which successfully generates a number of PDFs in a folder, and then compresses that folder into an unencrypted zip file.

I have used the code from a previous question:

https://www.telerik.com/forums/zip-content-of-a-folder-into-an-encrypted-zip-file

So my code is as follows:

public static void CreateZipFileFromDirectory(string sourceDirectoryName, string destinationArchiveFileName)

        {

            char[] directorySeparatorChar = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };

 

            ZipArchiveMode archiveMode = System.IO.File.Exists(destinationArchiveFileName) ? ZipArchiveMode.Update : ZipArchiveMode.Create;

 

            if (!string.IsNullOrEmpty(sourceDirectoryName))

            {

                using FileStream archiveStream = System.IO.File.Open(destinationArchiveFileName, FileMode.OpenOrCreate);

                using ZipArchive archive = new ZipArchive(archiveStream, archiveMode, leaveOpen: false, entryNameEncoding: null);

                foreach (string fileName in Directory.GetFiles(sourceDirectoryName))

                {

                    using FileStream file = System.IO.File.OpenRead(fileName);

                    int length = fileName.Length - sourceDirectoryName.Length;

                    string entryName = fileName.Substring(sourceDirectoryName.Length, length);

                    entryName = entryName.TrimStart(directorySeparatorChar);

 

                    using ZipArchiveEntry entry = archive.CreateEntry(entryName);

                    using Stream entryStream = entry.Open();

                    file.CopyTo(entryStream);

                }

            }

        }

This creates the zip file and adds the first PDF successfully, but gives an error when trying to add the second PDF

"The process cannot access the file 'filename.zip' because it is being used by another process."

I have tried setting the leaveOpen parameter for the ZipArchive to true and to false but that gives me the same error.

Any ideas what I've missed?

Richard

 

Dimitar
Telerik team
 answered on 01 Dec 2021
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?