Save pdf file with username (iTextSharp)
I want to allow the user to enter their own filename, as well as save the dialog and file 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 "ImageTest.pdf" part to be named as user with pdf extension (and .pdf filetype).
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("ImageTest.pdf", FileMode.Create));
Can anyone please help or does anyone have a better solution for my problem? I want to take a screenshot of my window form and export the image to pdf file under username
EDIT: With saveFileDialog (after bitmap.save) - Receive error "Format error: not 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();
}
}
source to share
I'm not an ITextSharp expert, but I think 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 selected in SaveFileDialog to the PdfWriter.GetInstance method
source to share