Paul_LayLow
Paul_LayLow

Reputation: 133

ABCPdf - Image not a suitable format

In the end, my goal is to send a raw image data from the front-end, then split that image into however many pages, and lastly send that pdf back to the front-end for download.

But every time I use the theDoc.addImageFile(), it tells me that the "Image is not in a suitable format". I'm using this as reference: https://www.websupergoo.com/helppdfnet/source/5-abcpdf/doc/1-methods/addimagefile.htm

To troubleshoot, I thought that the image might not be rendering correctly, so I added a File.WriteAllBytes to view the rendered image and it was exactly what I wanted, but still not adding to the PDF. I also tried sending the actual path of a previously rendered image thinking that the new image might not have been fully created yet, but it also gave me the same error. Lastly, I thought PNGs might be problematic and changed to JPG but it did not work.

Here is the code:

[HttpPost]
public IActionResult PrintToPDF(string imageString)
{
    // Converts dataUri to bytes
    var base64Data = Regex.Match(imageString, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
    var binData = Convert.FromBase64String(base64Data);

    /* Ultimately will be removed, but used for debugging image */
    string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string imgName= "Test.jpg";
    string filename = Path.Combine(path, imgName);

    System.IO.File.WriteAllBytes(filename, binData);
    /***********************************************************/

    using (Doc theDoc = new Doc())
    {
        // Using explicit path
        theDoc.AddImageFile(@"C:\Users\User\Documents\Test.jpg", 1);
        // Using variable
        //theDoc.AddImageFile(filename, 1);
        // What I really want
        //theDoc.AddImageFile(binData , 1);

        theDoc.Page = theDoc.AddPage();
        theDoc.AddText("Thanks");
        Response.Headers.Clear();
        Response.Headers.Add("content-disposition", "attachment; filename=test.pdf");
        return new FileStreamResult(theDoc.GetStream(), "application/pdf");
    }
}

Upvotes: 0

Views: 1601

Answers (2)

overprint
overprint

Reputation: 31

To add a JPEG from a byte array you need Doc.AddImageData instead of Doc.AddImageFile. Note that AddImageFile / AddImageData do not support PNG - for that you would definitely need to use an XImage. The XImage.SetData documentation has the currently supported image formats.

Upvotes: 0

Moose
Moose

Reputation: 5422

Try something like this (not tested, but cleaned up from my own code):

    public int AddImageFile(Doc doc, byte[] data, int insertBeforePageID)
    {
        int pageid;

        using (var img = new XImage())
        {
            img.SetData(data);

            doc.Page = doc.AddPage(insertBeforePageID);
            pageid = doc.Page;
            doc.AddImage(img);
            img.Clear();
        }
        return pageid;
    }

Upvotes: 1

Related Questions