4

I’m using WebSite in ASP.NET and iTextSharp PDF library. I have a tiff document image that contains 3 pages, I would want to convert all those 3 tiff pages into 1 PDF file with 3 pages.

I try this but it doesn't work as well...

Please tell me what should I do?

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

Document document = new Document();
using (var stream = new FileStream(@"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
    PdfWriter.GetInstance(document, stream);
    document.Open();
    using (var imageStream = new FileStream(@"C:\File\0.tiff", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        var image = iTextSharp.text.Image.GetInstance(imageStream);
        document.Add(image);
    }
    document.Close();
}
Javad Abedi
  • 492
  • 1
  • 6
  • 21
  • @mjwills this code converted just one page to PDF which I have 3 pages in that file and I should say that TIFF file is converting to PDF just small part of the picture – Javad Abedi Jun 12 '19 at 11:23
  • 1
    See [this answer](https://stackoverflow.com/a/30197789/3883866), the content of the foreach loop (`foreach (string image in files)`) – Jesse de Wit Jun 12 '19 at 11:39
  • @jesse-de-wit which part of my code? can you show as Answer? – Javad Abedi Jun 12 '19 at 11:47

3 Answers3

1
// creation of the document with a certain size and certain margins
iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);

// creation of the different writers
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(Server.MapPath("~/App_Data/result.pdf"), System.IO.FileMode.Create));

// load the tiff image and count the total pages
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(Server.MapPath("~/App_Data/source.tif"));
int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

document.Open();
iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
for (int k = 0; k < total; ++k)
{
    bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
    // scale the image to fit in the page
    img.ScalePercent(72f / img.DpiX * 100);
    img.SetAbsolutePosition(0, 0);
    cb.AddImage(img);
    document.NewPage();
}
document.Close();
0

I just copied the code from this answer, and modified it to your example. So credits go to the person who answered the question in the link.

using (var stream = new FileStream(@"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
    Document document = new Document(PageSize.A4, 0, 0, 0, 0);
    var writer = PdfWriter.GetInstance(document, stream);    
    var bitmap = new System.Drawing.Bitmap(@"C:\File\0.tiff"); 
    var pages = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

    document.Open();
    iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
    for (int i = 0; i < pages; ++i)
    {
        bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, i);
        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);
        // scale the image to fit in the page 
        //img.ScalePercent(72f / img.DpiX * 100);
        //img.SetAbsolutePosition(0, 0);
        cb.AddImage(img);
        document.NewPage();
    }
   }
   document.Close();
}
Jesse de Wit
  • 3,867
  • 1
  • 20
  • 41
  • thank you pal but please tell me how should I fit image in the pages of PDF. now I converted the TIFF file to PDF but the PDF file doesn't open and has error :( – Javad Abedi Jun 12 '19 at 12:49
  • Did you uncomment the scaling and position part? Also, added the document size in the second line of code. – Jesse de Wit Jun 12 '19 at 12:51
  • Yeah. I write your sample and execute the program and it worked without error but the result PDF, not opened – Javad Abedi Jun 12 '19 at 12:56
  • Perhaps if you try to add the pagesize in the document. See updated answer. Or make scalepercent really small? – Jesse de Wit Jun 12 '19 at 13:00
  • I should say I want to converting TIFF file with Variable Size. – Javad Abedi Jun 12 '19 at 13:02
  • Just try to make them really small first, and see if that works. If so, you can start worrying about variable sizes. – Jesse de Wit Jun 12 '19 at 13:05
  • OK , this is a detail of my example Multi page TIFF file : dimension : 869*1229 - width: 869 pixels - height: 1229 pixels - horizontal resolution: 150 dpi - vertical resolution: 150 dpi - Bit depth: 8 - Compression : LZW - resolution unit: 2 - – Javad Abedi Jun 12 '19 at 13:09
  • 1
    Try 70f. If that doesn't work, try 3f, just to make sure the size is the problem. If that does not work, I'm afraid I'm not able to help you with this. – Jesse de Wit Jun 12 '19 at 13:14
  • I think the size is the main problem :( because program is running without any error but the result has a problem. I try as you said but PDF not open. – Javad Abedi Jun 12 '19 at 13:22
  • So, did you try 3f? – Jesse de Wit Jun 12 '19 at 14:02
  • Yeah, all of them(70f,3f,72f,..) but still not working – Javad Abedi Jun 12 '19 at 14:08
0

What I achieved after a long period and based on some searches.

I make a request and the response is PDF or TIFF. The first part is just what I get and how I call the private methods, and that is what you need.

var httpResponse = (HttpWebResponse)(await httpWebRequest.GetResponseAsync());
Stream stream = httpResponse.GetResponseStream();
string contentType = httpResponse.ContentType;
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
FileStream file2;
try
{
    switch (contentType)
    {
        case "application/pdf":
            {

                string outputfile2 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".pdf");
                file2 = new FileStream(outputfile2, FileMode.Create, FileAccess.Write);
                ms.WriteTo(file2);
                file2.Close();
                break;
            }

        default:
            {


                string outputfile1 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".tiff");
                file2 = new FileStream(outputfile1, FileMode.Create, FileAccess.Write);
                ms.WriteTo(file2);
                file2.Close();

                string[] outfilesTiffPages = ConvertTiffToJpeg(outputfile1);
                File.Delete(outputfile1);

                string outputfile2 = Path.Combine(zipDirectory, "ixosid_" + icxos + ".pdf");
                iTextSharp.text.Document doc= AddPicturesToPDF(outfilesTiffPages, outputfile2);
                
                break;
            }

    }
}

and I have two private methods

private string[] ConvertTiffToJpeg(string fileName)
{
    using (System.Drawing.Image imageFile = System.Drawing.Image.FromFile(fileName))
    {
        FrameDimension frameDimensions = new FrameDimension(
            imageFile.FrameDimensionsList[0]);

        // Gets the number of pages from the tiff image (if multipage) 
        int frameNum = imageFile.GetFrameCount(frameDimensions);
        string[] jpegPaths = new string[frameNum];

        for (int frame = 0; frame < frameNum; frame++)
        {
            // Selects one frame at a time and save as jpeg. 
            imageFile.SelectActiveFrame(frameDimensions, frame);
            using (Bitmap bmp = new Bitmap(imageFile))
            {
                jpegPaths[frame] = String.Format(@"{0}\{1}{2}.jpg",
                    Path.GetDirectoryName(fileName),
                    Path.GetFileNameWithoutExtension(fileName),
                    frame);
                bmp.Save(jpegPaths[frame], ImageFormat.Jpeg);
            }
        }

        return jpegPaths;
    }
}

private iTextSharp.text.Document AddPicturesToPDF(string[] filesPaths, string outputPdf)
{
    FileStream fs = new FileStream(outputPdf, FileMode.Create);
    Document pdfdoc = new Document();
    PdfWriter.GetInstance(pdfdoc, fs);
    pdfdoc.Open();
    int size = filesPaths.Length;
    int count = 0;
    foreach(string imagePath in filesPaths)
    {
        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
        img.Alignment = Element.ALIGN_CENTER;
        img.SetAbsolutePosition(0, 0);
        img.ScaleToFit((PageSize.A4.Width - pdfdoc.RightMargin - pdfdoc.LeftMargin), (PageSize.A4.Height- pdfdoc.BottomMargin - pdfdoc.TopMargin));
        pdfdoc.Add(img);
        pdfdoc.NewPage();

    }           
    pdfdoc.Close();
    return pdfdoc;
}

Maybe I can work with MemoryStream but for now, is working and is what I need.

I searched a lot, and some links that deserve to be mentioned

https://coderedirect.com/questions/178295/convert-tiff-to-jpg-format