Is there a way to convert single and multi-page Tiff to PDF with PdfSharpCore in .NET 6?

Viewed 20

Updated: Adding my new code that has issues

I am still new to .NET 6 and am currently trying to replace PdfSharp-GDI and System.Drawing with PdfSharpCore due to various warnings with PdfSharp (last update was 2019 from the NuGet page) and System.Drawing due to breaking changes with .NET 6.

My issue is converting both single and multipage Tiff files to Pdf.

I was originally able to achieve the conversion with PdfSharp-GDI and System.Drawing using the following code but am struggling to develop equivalent code with PdfSharpCore.

private static Drawing TifToPdf(string tifData)
{
    string drawing = "";
    byte[] data = Convert.FromBase64String(tifData);
    byte[] convertedData;
    using (MemoryStream inStream = new MemoryStream(data))
    using (MemoryStream outStream = new MemoryStream())
    {
        System.Drawing.Image MyImage = System.Drawing.Image.FromStream(inStream);
        PdfDocument doc = new PdfDocument();

        for (int PageIndex = 0; PageIndex < MyImage.GetFrameCount(FrameDimension.Page); PageIndex++)
        {
            MyImage.SelectActiveFrame(FrameDimension.Page, PageIndex);
            XImage img = XImage.FromGdiPlusImage(MyImage);
            var page = new PdfPage();
            doc.Pages.Add(page);
            XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
            xgr.DrawImage(img, 0, 0);
        }

        doc.Save(outStream);
        MyImage.Dispose();
        convertedData = outStream.ToArray();
        drawing = convertedData;
    }

    return drawing;
}

My new code is the following but it does not work because of a lack of a TiffDecoder and something is wrong with the conversion:

private static Drawing TifToPdf(string tifData)
{
    string drawing = "";
    byte[] data = Convert.FromBase64String(tifData);
    byte[] convertedData;
    using (MemoryStream inStream = new MemoryStream(data))
    using (MemoryStream outStream = new MemoryStream())
    {
     // new code
            PdfDocument doc = new PdfDocument();
            XImage img = XImage.FromStream(() => inStream);
            var page = doc.AddPage();
            XGraphics xgr = XGraphics.FromPdfPage(page);
            xgr.DrawImage(img, 0, 0);
            doc.Save(outStream);
            convertedData = outStream.ToArray();
            drawingFile = Convert.ToBase64String(convertedData);
    // end of new code
    }

    return drawing;
}

How can I convert a Tif (single and multipage) to pdf?

If you need more information, please let me know. Thanks!

0 Answers
Related