I create a PDF and add Textbox Form Field inside the pdf and give name such as "#name#, which later in the Controller I put the values.
My code
public FileResult Test(EventArgs e)
{
string TemplateLoc = "templates\\test.pdf";)
var stream = new MemoryStream();
string sourceFile = Path.Combine(path);
string destinationFile = Path.Combine(_hostingEnvironment.WebRootPath, "templates\\temp" + ".pdf");
System.IO.File.Copy(sourceFile, destinationFile);
Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("#name#", "test");
using (var existingFileStream = new FileStream(sourceFile, FileMode.Open))
using (var newFileStream = new FileStream(destinationFile, FileMode.Create))
{
var pdfReader = new PdfReader(existingFileStream);
var stamper = new PdfStamper(pdfReader, newFileStream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
foreach (string fieldKey in fieldKeys)
{
foreach (KeyValuePair<string, string> i in keyValues)
{
if (fieldKey == i.Key)
{
form.SetField(fieldKey, i.Value);
}
}
}
stamper.FormFlattening = true;
stamper.Close();
pdfReader.Close();
}
byte[] fileBytes = System.IO.File.ReadAllBytes(destinationFile);
System.IO.File.Delete(destinationFile);
string fileName = "test" + ".pdf";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Instead of appending the text box field, I need to add a Picture/Image from my Desktop to the document, let's say adding Photo in a specific location of the document.