I have the following code (C#) for generating a PDF using iTextSharp. This code
ID: 3742063 • Letter: I
Question
I have the following code (C#) for generating a PDF using iTextSharp. This code currently svaes thePDF however I need it to automatically name the filename to the contents in txtID.Text. For example if the contents added in the txtID.Text is E1234, I want the file to automatically add the E1234 to the filename so the file will be E1234.pdf. I have tried a couple of things but with no luck.
Here is my current code without any auto naming included:
private void btnCreatePDF_Click(object sender, EventArgs e)//transfers data displayed in txtDisplay.Text into a PDF
{
using (SaveFileDialog sfd = new SaveFileDialog()
{
Filter = "PDF file|*.pdf", ValidateNames = true })
{
if (sfd.ShowDialog() == DialogResult.OK)
{
iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
try
{
PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
doc.Open();
doc.Add(new iTextSharp.text.Paragraph(txtDisplay.Text));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
doc.Close();
}
}
}
}
Explanation / Answer
private void btnCreatePDF_Click(object sender, EventArgs e) //transfers data displayed in txtDisplay.Text into a PDF
{
using(SaveFileDialog sfd = new SaveFileDialog() {
Filter = "PDF file|*.pdf", ValidateNames = true
})
{
if (sfd.ShowDialog() == DialogResult.OK)
{
iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
try {
string path;
path = Path.Combine(Path.GetDirectoryName(sfd.FileName), Path.GetFileNameWithoutExtension(sfd.FileName) + "." + txtID.Text + ".pdf");
/*
we build the path we get from the System File Dialog
import System.IO to use the Path class first
Suppose the path we get is C:olderilename.pdf
First we get the directory name: C:older
Then the filename without extension: filename
Then we get the text from the text box (For example E1234)
And add the pdf extension to it: E1234.pdf
Now add it to the filename without the extension: filename.E1234.pdf
Then combine it with the the directory path: C:olderilename.E1234.pdf
Now use this string to create the PDF
NOTE: if you don't want to append the text to filename and just
want the text to be the filename use:
path = Path.Combine(Path.GetDirectoryName(sfd.FileName), txtID.Text + ",pdf");
Path.Combine() takes multiple paths / filenames as input
to create a single path
*/
PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
doc.Open();
doc.Add(new iTextSharp.text.Paragraph(txtDisplay.Text));
} catch (Exception ex) {
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
} finally {
doc.Close();
}
}
}
}