0

I am using Libtiff.net and PdfSharp to convert multi-page TIF to PDF. The problem I have is that I cannot appear to get the data of a current page/directory and convert it to a byte array in order to pass to XImage.FromStream(myStream). Instead, the code I have writes the same page multiple times rather than each individual page. I cannot use System.Drawing.Common because it is deprecated in the version of .NET I am using. Thanks!

byte[] data = System.IO.File.ReadAllBytes("img.tif");
PdfDocument d = new PdfDocument();

using (MemoryStream ms = new MemoryStream(data))
using (Tiff t = Tiff.ClientOpen("test", "r", ms, new TiffStream()))
{
  int c = t.NumberOfDirectories();
  for (int i = 0; i < c; i++)
  {
    t.SetDirectory((short)i);
    PdfPage p = d.AddPage();
    XGraphics g = XGraphics.FromPdfPage(p);
    XImage img = XImage.FromStream(ms);
    p.Width = img.PointWidth;
    p.Height = img.PointHeight;
    g.DrawImage(img, 0, 0);
  }
}
usagibear
  • 303
  • 3
  • 12
  • Maybe this post helps - it shows how to extract individual pages, but saves them to BMP files instead of PDF pages: https://stackoverflow.com/a/13178821/162529 It is easy to use BMP files with PDFsharp. – I liked the old Stack Overflow Feb 09 '23 at 08:52
  • Thank you for the help. Unfortunately, I cannot use that method because System.Drawing.Common is not cross-platform and current versions of .NET do not allow using it on Linux. I was hoping there was a way to get the byte data from each directory in the Tiff. – usagibear Feb 14 '23 at 00:07
  • The code shows how to get the byte data for each directory in the TIFF. Turning it into something useful can be done with a few lines of code even without System.Drawing.Common. Write a BITMAPINFOHEADER into a stream or byte[], append the byte data, and use it even under Linux. – I liked the old Stack Overflow Feb 14 '23 at 07:43
  • An easy way to convert images like TIF to multi-page PDF is to use the LEADTOOLS Imaging SDK. (Disclosure: I work for the SDK's vendor.) The code consists of simply calling `RasterCodecs.Load()` to load the input images then `RasterCodecs.Save()` to save as PDF. The same C# code can be used on Linux and other platforms such as Windows. If you'd like to try it, you can download a free evaluation [here](https://www.leadtools.com/downloads) that comes with documentations, sample code and free technical support. – Amin Dodin Apr 20 '23 at 15:05

0 Answers0