ImageMagick.NET library multipage TIFF to PDF

219 Views Asked by At

I'm having an issue where rather small tiff files (< 300 KB) gets blown up to like 74 MB when converted into a PDF.

using (var img_collection = new MagickImageCollection())
{
      using (var tif_collection = new MagickImageCollection(Convert.FromBase64String(base64_string_of_tif_image), MagickFormat.Tif))
      {
            foreach (MagickImage tif in tif_collection)
            {
                  img_collection.Add(new MagickImage(tif.ToByteArray())
                  {
                       Format = MagickFormat.Pdf                                    
                  });
             }    
             tif_collection.Dispose();
       }

       img_collection.Write("output.pdf", MagickFormat.Pdf);
       img_collection.Dispose();
 }

Any ideas as to how I can prevent that from happening? The tif files are actually just scans of text.

1

There are 1 best solutions below

0
Aidal On

I was not able to resolve the issues with the library I was using ImageMagick.NET, so the solution I found was to switch to another library which I had previous been using for other tasks, PDFSharp (pdfsharp-migradoc-gdi to be exact).

The new code to perform the same task with PDFSharp, goes like this:

using (MemoryStream strm = new MemoryStream(Convert.FromBase64String(base64EncodedString)))
{
    strm.Position = 0;

    using (Image MyImage = Image.FromStream(strm))
    {
        using (PdfSharp.Pdf.PdfDocument doc = new PdfSharp.Pdf.PdfDocument())
        {
            for (int PageIndex = 0; PageIndex < MyImage.GetFrameCount(FrameDimension.Page); PageIndex++)
            {
                MyImage.SelectActiveFrame(FrameDimension.Page, PageIndex);

                PdfSharp.Drawing.XImage img = PdfSharp.Drawing.XImage.FromGdiPlusImage(MyImage);

                var page = new PdfSharp.Pdf.PdfPage();

                if (img.PixelWidth > img.PixelHeight)
                {
                    page.Orientation = PdfSharp.PageOrientation.Landscape;
                }
                else
                {
                    page.Orientation = PdfSharp.PageOrientation.Portrait;
                }
                doc.Pages.Add(page);

                PdfSharp.Drawing.XGraphics xgr = PdfSharp.Drawing.XGraphics.FromPdfPage(doc.Pages[PageIndex]);

                xgr.DrawImage(img, 0, 0);
            }

            doc.Save(outputFilePath);
            doc.Close();
        }
    }

    strm.Close();
}

I hope this can help someone else experiencing the same issues with large PDF files when converting from TIF.