Telerik Forums
Telerik Document Processing Forum
0 answers
46 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
134 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
47 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
71 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
38 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
55 views

Hi,

 

I have an existing xlsx file that contains graphics (drawing)

I simply open the workbook, 


var workbook = CreateWorkbook();

byte[] bytes;

using (var output = new MemoryStream())
{
    new XlsxFormatProvider().Export(workbook, output);
    bytes = output.ToArray();
}

File.WriteAllBytes("c:\\Logs\\test.xlsx", bytes);


private Workbook CreateWorkbook()
{
    Workbook workbook;
    IWorkbookFormatProvider formatProvider = new XlsxFormatProvider();
    FileStream? stream = null;
    try
    {
        stream = File.Open("AnalyseImpayeTemplate.xlsx", FileMode.Open);
        workbook = formatProvider.Import(stream);
    }
    catch (IOException ex)
    {
        throw new IOException("The file cannot be opened. It might be locked by another application.", ex);
    }
    finally
    {
        stream?.Dispose();
    }

    return workbook;
}

When I open the result file, with release 2024.3.806, I got an error. It delete drawing parts :

Partie supprimée: /xl/drawings/drawing1.xml partie.  (Forme de dessin)

With release 2024.2.426, it works fine.

Any ideas why?

Yoan
Telerik team
 answered on 08 Oct 2024
1 answer
67 views

I'm able to export data to an .xlsx file.  That file is exported to E:/SaoApps/Sims/wwwroot/exports and the user has full control over that folder.  The file successfully is created at that location.  But the file doesn't open or offer download to the user and the error message is:

In the attached code snippet, the passed exportsFolder = "E:/SaoApps/Sims/wwwroot/exports/" and passed lanId = "DSS"

"An error occurred trying to start process 'E:/SaoApps/Sims/wwwroot/exports/ContactsSearchResults_DSS.xlsx' with working directory 'E:\\Workspace\\Intranet\\Sims\\Sims'. The process cannot access the file because it is being used by another process."

 

System.ComponentModel.Win32Exception (32): An error occurred trying to start process 'E:/SaoApps/Sims/wwwroot/exports/ContactsSearchResults_DSS.xlsx' with working directory 'E:\Workspace\Intranet\Sims\Sims'. The process cannot access the file because it is being used by another process.
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at Sims.Agency.Data.Services.AgencyExportService.ExportContactSearchResults(String criteria, List`1 searchResults) in E:\Workspace\Intranet\Sims\Sims.Agency.Data\Services\AgencyExportService.cs:line 424
   at Sims.Contacts.Pages.ContactSearchBase.ExportToExcel() in E:\Workspace\Intranet\Sims\Sims.Contacts\Pages\ContactSearchBase.cs:line 327
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
Yoan
Telerik team
 answered on 12 Apr 2024
1 answer
119 views

Hello,

I am trying to upload the stream object received from the 'ToXlsxStream' method of Telerik SpreadSheet processing library to Azure blob container. Unfortunately, it is saving as a blank excel file. I have data in the List object which is getting converted to xlsx stream. Not sure why the excel file is blank. Tried to save the stream to my local file explorer as well. Still, the issue persists. 

Below is the code:

 

  try
   {
Stream exportStream = exportFormat == SpreadDocumentFormat.Xlsx ? workOrderList.ToXlsxStream(columnsData, (string)options.title.ToString(), cellStyleAction: cellStyle) : workOrderList.ToCsvStream(columnsData);

Task.Factory.StartNew(() => AzureHelper.UploadReportOnCloud(exportStream,fileName, ConfigurationManager.AppSettings[Constant.REPORTATTACHMENTCONTAINER]));

}

            catch(Exception ex)
            {

            }

 

Please help me to resolve this issue.  

Dess | Tech Support Engineer, Principal
Telerik team
 answered on 18 Dec 2023
1 answer
127 views

Hello,

I have a corrupted XLSX file from CSV dataSource

With other CSV dataSource all is ok

In example in file-attach, I added CSV dataSource with corruption

There are 2 bad lines in generated XLSX file and CSV file have a good format !!!

It's not an issue with codepage or separator !

It's a projet DotNet Core 6 with last version 2023.2.713.20 of API

Do you have encountered this error already ?

Best regards

Cyril REILER

 

 

 

Cyril
Top achievements
Rank 1
Iron
 updated answer on 26 Sep 2023
1 answer
393 views


Hi all, 

I got some problems when I try to read my Excel file as below:

1. It skipped the null cells, it only read data at the cells having value. For example in my case, after reading cell 2 at row 2, it jumped to cell 14. 

2. It showed the error message "The given key '3' was not present in the dictionary." at cell 15

You can see my code, the Excel file I used, and the result in below

My code

@page "/testpage"
@using Telerik.Documents.SpreadsheetStreaming;
<div>
    @((MarkupString)(str.ToString()))
</div>


@code {
    private StringBuilder str = new StringBuilder();
    protected override void OnInitialized()
    {
        str = ReadData();
    }
    private StringBuilder ReadData()
    {

        try
        {
            string filename = ".\\Template.xlsx";
            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                using (IWorkbookImporter workBookImporter = SpreadImporter.CreateWorkbookImporter(SpreadDocumentFormat.Xlsx, fs))
                {
                    foreach (IWorksheetImporter worksheetImporter in workBookImporter.WorksheetImporters)
                    {
                        foreach (IRowImporter rowImporter in worksheetImporter.Rows)
                        {
                            foreach (ICellImporter cell in rowImporter.Cells)
                            {
                                if(cell.Value!= null)
                                {
                                    str.Append(cell.Value.ToString());

                                }
                                else
                                {
                                    str.Append("NULL");
                                }
                                str.Append(",");
                            }
                            str.Append("<br/>");
                        }

                    }
                }
            }
            return str;
        }
        catch(Exception ex)
        {
            str.Append("<br/>");
            str.Append(ex.Message);
            return str;
        }

    }
}
 My Excel file as a picture below, I also attached my Excel in the question (Template.rar)

  The result when I run 

  Everyone who know how to fix it, please help me.

Thank you

Yoan
Telerik team
 answered on 04 Jul 2023
Narrow your results
Selected tags
Tags
+? more
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?