Save pdf file with user input filename (iTextSharp)

dodoria1992 picture dodoria1992 · May 15, 2015 · Viewed 13.4k times · Source

I want to allow user to enter his own file name, just like save file dialog and stream (Example: Stream s = File.Open(sfdPdf.FileName, FileMode.CreateNew)

Here is my code:

    private void btnSave_Click(object sender, EventArgs e)
    {

        System.Drawing.Rectangle bounds = this.Bounds;
        using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
        {
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
            }
            bitmap.Save("Image.jpeg", ImageFormat.Jpeg);
        }

        Document doc = new Document(PageSize.LETTER, bounds.Left, bounds.Right, bounds.Top, bounds.Bottom);
        PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("ImageTest.pdf", FileMode.Create));
        doc.Open();
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("Image.jpeg");
        doc.Add(image);
        doc.Close();
}

I want the part "ImageTest.pdf" to be named as the user want with pdf extension (and .pdf filetype).

PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("ImageTest.pdf", FileMode.Create));

Can anyone help or does anyone has better solution for my problem? I want to take screenshot of my windows form and export image to pdf file under user input name

EDIT: With saveFileDialog (after bitmap.save) - Receiving error "Format Error: Not a PDF or corrupted."

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Pdf File |*.pdf";
if (sfd.ShowDialog() == DialogResult.OK)
{
    using (Stream s = File.Open(sfd.FileName, FileMode.CreateNew))
    {
        Document doc = new Document(PageSize.LETTER, bounds.Left, bounds.Right, bounds.Top, bounds.Bottom);
        PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("ImageTest.pdf", FileMode.Create));
        doc.Open();
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("Image.jpeg");
        doc.Add(image);
        doc.Close();
        s.Close();
        s.Dispose();
    }               
}

Answer

Steve picture Steve · May 15, 2015

I am not an expert of ITextSharp, but I think that your code should be something like this

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Pdf File |*.pdf";
if (sfd.ShowDialog() == DialogResult.OK)
{
    Document doc = new Document(PageSize.LETTER, bounds.Left, bounds.Right, bounds.Top, bounds.Bottom);
    PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
    doc.Open();
    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("Image.jpeg");
    doc.Add(image);
    doc.Close();
}

In other words, just pass the FileName string choosen in SaveFileDialog to the PdfWriter.GetInstance method