I have an ASP.net web form application and I have a page that would download a PDF-A3 file created from an HTML string, when I run the appliaction on debug from my device it works perfectly but when I publish the app and put it on the IIS on the server it always throws an error which says:
Message: The document has no pages.
Stack_Trace: at iTextSharp.text.pdf.PdfPages.WritePageTree() at iTextSharp.text.pdf.PdfWriter.Close() at iTextSharp.text.pdf.PdfAWriter.Close() at iTextSharp.text.Document.Close() at Common.PDFHelper.GeneratePDF(String html, String fileName, Boolean isNormalPDF, String detailsJSON) in C:\Libraries\Common\PDFHelper.cs:line 135
I tried at the same time to download a normal PDF and it works fine, but as I said the PDF-A type only works on debug but on release publish build it throws an error.
here is my code:
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web;
namespace Common
{
public class PDFHelper
{
public void GeneratePDF(string html, string fileName = "", bool isNormalPDF = false, string detailsJSON = "")
{
try
{
if (string.IsNullOrWhiteSpace(fileName))
fileName = Helpers.GenerateRandomString(8);
fileName += Guid.NewGuid().ToString();
int imageIndex = html.IndexOf("data:image/jpeg;base64");
string imageURL = "";
if (imageIndex > -1)
{
try
{
int imageSourceEndIndex = html.IndexOf("\"", imageIndex);
string imageBase64 = html.Substring(imageIndex, imageSourceEndIndex - imageIndex);
imageBase64 = imageBase64.Substring(imageBase64.IndexOf(",") + 1);
byte[] imageBytes = Convert.FromBase64String(imageBase64);
imageURL = HttpContext.Current.Server.MapPath(fileName + ".jpg");
File.WriteAllBytes(imageURL, imageBytes);
html = html.Remove(imageIndex, imageSourceEndIndex - imageIndex);
html = html.Insert(imageIndex, imageURL);
}
catch (Exception ex)
{
MStartLogger.Error(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, "");
}
}
string xmlFile = "";
byte[] bytes;
using (MemoryStream memoryStream = new MemoryStream())
{
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(Environment.GetFolderPath(Environment.SpecialFolder.Fonts));
if (isNormalPDF)
{
Document pdfDoc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
var xmlWorker = XMLWorkerHelper.GetInstance();
MemoryStream htmlContent = new MemoryStream(Encoding.UTF8.GetBytes(html));
xmlWorker.ParseXHtml(writer, pdfDoc, htmlContent, null, Encoding.UTF8, fontProvider);
pdfDoc.Close();
}
else
{
Document pdfDoc = new Document(PageSize.A4);
PdfAWriter writer = PdfAWriter.GetInstance(pdfDoc, memoryStream, PdfAConformanceLevel.PDF_A_3A);
pdfDoc.Open();
writer.CreateXmpMetadata();
string sRGBCSprofile = HttpContext.Current.Server.MapPath("~/Resources/Color/sRGB_CS_profile.icm");
FileStream sRGBCSproFileStream = new FileStream(sRGBCSprofile, FileMode.Open, FileAccess.Read);
var sRGBCSproFileByte = new byte[sRGBCSproFileStream.Length];
sRGBCSproFileStream.Read(sRGBCSproFileByte, 0, sRGBCSproFileByte.Length);
ICC_Profile iccProfile = ICC_Profile.GetInstance(sRGBCSproFileByte);
writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", iccProfile);
PdfDictionary markInfo = new PdfDictionary(PdfName.MARKINFO);
markInfo.Put(PdfName.MARKED, new PdfBoolean("true"));
writer.ExtraCatalog.Put(PdfName.MARKINFO, markInfo);
string xmlString = "";
if (!string.IsNullOrWhiteSpace(xmlString))
{
try
{
xmlFile = HttpContext.Current.Server.MapPath(fileName + ".xml");
File.WriteAllText(xmlFile, xmlString, Encoding.ASCII);
}
catch (Exception ex)
{
Error(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, "");
}
}
if (!string.IsNullOrWhiteSpace(xmlFile))
{
PdfDictionary parameters = new PdfDictionary();
parameters.Put(PdfName.MODDATE, new PdfDate());
PdfFileSpecification fileSpec = PdfFileSpecification.FileEmbedded(writer, xmlFile, "invoice.xml", null, "application/xml", parameters, 0);
fileSpec.Put(new PdfName("AFRelationship"), new PdfName("Data"));
writer.AddFileAttachment("Invoice Xml", fileSpec);
PdfArray array = new PdfArray();
array.Add(fileSpec.Reference);
writer.ExtraCatalog.Put(new PdfName("AF"), array);
}
var xmlWorker = XMLWorkerHelper.GetInstance();
MemoryStream htmlContent = new MemoryStream(Encoding.UTF8.GetBytes(html));
xmlWorker.ParseXHtml(writer, pdfDoc, htmlContent, null, Encoding.UTF8, fontProvider);
pdfDoc.Close();
}
bytes = memoryStream.ToArray();
memoryStream.Close();
}
// Clears all content output from the buffer stream
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.BinaryWrite(bytes);
// Delete the temp image.
if (!string.IsNullOrWhiteSpace(imageURL))
File.Delete(imageURL);
if (!string.IsNullOrWhiteSpace(xmlFile))
File.Delete(xmlFile);
HttpContext.Current.Response.End();
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
Error(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, "");
}
}
}
}
Related
Using c# and iText7 I need to modify an existing PDF and save it to blob storage.
I have a console app that does exactly what I need using the file system:
PdfReader reader = new PdfReader(source);
PdfWriter writer = new PdfWriter(destination2);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
fields = form.GetFormFields();
fields.TryGetValue("header", out PdfFormField cl);
var type = cl.GetType();
cl.SetValue("This is a header");
pdfDoc.Close();
This works just fine. However I can not figure out how to do the same thing pulling the PDF from blob storage and sending the new one to blob storage
IDictionary<string, PdfFormField> fields;
MemoryStream outStream = new MemoryStream();
var pdfTemplate = _blobStorageService.GetBlob("mycontainer", "TestPDF.pdf");
PdfReader reader = new PdfReader(pdfTemplate);
PdfWriter writer = new PdfWriter(outStream);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
fields = form.GetFormFields();
fields.TryGetValue("header", out PdfFormField cl);
cl.SetValue("This is a header");
pdfDoc.Close();
outStream.Position = 0;
_blobStorageService.UploadBlobAsync("mycontainer", **THIS IS THE ISSUE**, "newpdf.pdf");
I think I need to get pdfDoc as a byte array. Outstream is incorrect, it is only has a length of 15
The code below shows how to read a PDF from a file into a byte[] and also how to modify a PDF that's stored as a byte[].
Download and install NuGet package: iText7
In Solution Explorer, right-click <project name> and select Manage NuGet Packages...
Click Browse
In the search box type: iText7
Select iText7
Select desired version
Click Install
Add the following using statements:
using System.IO;
using iText.Kernel.Pdf;
using iText.Forms;
using iText.Forms.Fields;
Get PDF as byte[] (GetPdfBytes):
public static Task<byte[]> GetPdfBytes(string pdfFilename)
{
byte[] pdfBytes = null;
using (PdfReader reader = new PdfReader(pdfFilename))
{
using (MemoryStream msPdfWriter = new MemoryStream())
{
using (PdfWriter writer = new PdfWriter(msPdfWriter))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
//don't close underlying streams when PdfDocument is closed
pdfDoc.SetCloseReader(false);
pdfDoc.SetCloseWriter(false);
//close
pdfDoc.Close();
//set value
msPdfWriter.Position = 0;
//convert to byte[]
pdfBytes = msPdfWriter.ToArray();
}
}
}
}
return Task.FromResult(pdfBytes);
}
Usage:
byte[] pdfBytes = null;
string filename = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF File (*.pdf)|*.pdf";
if (ofd.ShowDialog() == DialogResult.OK)
{
//get PDF as byte[]
var tResult = GetPdfBytes(ofd.FileName);
pdfBytes = tResult.Result;
//For testing, write back to file so we can ensure that the PDF file opens properly
//create a new filename
filename = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName) + " - Test.pdf";
filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ofd.FileName), filename);
//save to file
File.WriteAllBytes(filename, pdfBytes);
System.Diagnostics.Debug.WriteLine("Saved as '" + filename + "'");
}
Modify PDF that's stored in a byte[] (ModifyPdf)
public static Task<byte[]> ModifyPdf(byte[] pdfBytes)
{
byte[] modifiedPdfBytes = null;
using (MemoryStream ms = new MemoryStream(pdfBytes))
{
using (PdfReader reader = new PdfReader(ms))
{
using (MemoryStream msPdfWriter = new MemoryStream())
{
using (PdfWriter writer = new PdfWriter(msPdfWriter))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
//don't close underlying streams when PdfDocument is closed
pdfDoc.SetCloseReader(false);
pdfDoc.SetCloseWriter(false);
//get AcroForm from document
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
//get form fields
IDictionary<string, PdfFormField> fields = form.GetFormFields();
//for testing, show all fields
foreach (KeyValuePair<string, PdfFormField> kvp in fields)
{
System.Diagnostics.Debug.WriteLine("Key: '" + kvp.Key + "' Value: '" + kvp.Value + "'");
}
PdfFormField cl = null;
//get specified field
fields.TryGetValue("1 Employee name", out cl);
//set value for specified field
cl.SetValue("John Doe");
//close PdfDocument
pdfDoc.Close();
//set value
msPdfWriter.Position = 0;
//convert to byte[]
modifiedPdfBytes = msPdfWriter.ToArray();
}
}
}
}
}
return Task.FromResult(modifiedPdfBytes);
}
Usage:
byte[] pdfBytes = null;
string filename = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF File (*.pdf)|*.pdf";
if (ofd.ShowDialog() == DialogResult.OK)
{
//get PDF as byte[]
var tResult = GetPdfBytes(ofd.FileName);
pdfBytes = tResult.Result;
//modify PDF
pdfBytes = await ModifyPdf(pdfBytes);
//create a new filename
filename = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName) + " - TestModified.pdf";
filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ofd.FileName), filename);
//save to file
File.WriteAllBytes(filename, pdfBytes);
System.Diagnostics.Debug.WriteLine("Saved as '" + filename + "'");
}
The code below is adapted from Sample01b_HelloWorldAsync.cs and is untested.
Download and install NuGet package: Azure.Storage.Blobs
Add the following using statement:
using Azure.Storage.Blobs;
DownloadPdf:
public static async Task<byte[]> DownloadPdf(string connectionString, string blobContainerName, string blobName)
{
byte[] pdfBytes = null;
using (MemoryStream ms = new MemoryStream())
{
// Get a reference to the container and then create it
BlobContainerClient container = new BlobContainerClient(connectionString, blobContainerName);
Azure.Response<Azure.Storage.Blobs.Models.BlobContainerInfo> responseCA = await container.CreateAsync();
// Get a reference to the blob
BlobClient blob = container.GetBlobClient(blobName);
// Download the blob's contents and save it to a file
Azure.Response responseDTA = await blob.DownloadToAsync(ms);
//set value
ms.Position = 0;
//convert to byte[]
pdfBytes = ms.ToArray();
}
return pdfBytes;
}
UploadPdf:
public static async Task<Azure.Response<Azure.Storage.Blobs.Models.BlobContentInfo>> UpdloadPdf(byte[] pdfBytes, string connectionString, string blobContainerName, string blobName)
{
Azure.Response<Azure.Storage.Blobs.Models.BlobContentInfo> result = null;
using (MemoryStream ms = new MemoryStream(pdfBytes))
{
//this statement may not be necessary
ms.Position = 0;
// Get a reference to the container and then create it
BlobContainerClient container = new BlobContainerClient(connectionString, blobContainerName);
await container.CreateAsync();
// Get a reference to the blob
BlobClient blob = container.GetBlobClient(blobName);
//upload
result = await blob.UploadAsync(ms);
}
return result;
}
Here's a PDF file for testing.
I have generated a pdf file from html and now I need to save it to a folder in my project.
I am able to get the generated pdf to download locally but when I send it to the file folder it gets corrupted and will not open.
public void CreateHTML(ComplaintIntakeData cd)
{
string formHtml = "<table class=\"MsoNormal\">";
string complaintTypeHtml = PCSUtilities.GetComplaintTypeHTML(cd);
string providerHtml = "";
if (cd.Providers != null && cd.Providers.Count > 0)
{
providerHtml = PCSUtilities.GetProviderHTML(cd);
}
string facilityHtml = PCSUtilities.GetFacilityHTML(cd);
string anonymousHtml = PCSUtilities.GetAnonymousHTML(cd);
string contactHtml = PCSUtilities.GetContactHTML(cd);
string patientHtml = PCSUtilities.GetPatientHTML(cd);
string detailsHtml = PCSUtilities.GetComplaintDetailsHTML(cd);
formHtml = formHtml + complaintTypeHtml + providerHtml + facilityHtml + anonymousHtml + contactHtml + patientHtml + detailsHtml + "</table>";
formHtml = formHtml.Replace("''", "\"");
// Load HTML template for letter and replace template fields with provider data
string htmlContent = File.ReadAllText(Server.MapPath("~/ComplaintIntakeForm.html"));
htmlContent = htmlContent.Replace("<%ComplaintInformation%>", formHtml);
string fileName = "ComplaintIntakeFile_" + cd.ComplaintGuid.ToString() +".pdf";
using (MemoryStream memStream = new MemoryStream())
{
try
{
// Load up a new PDF doc.
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memStream);
// writer.CompressionLevel = PdfStream.NO_COMPRESSION;
// Make document tagged PDFVERSION_1_7
writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
writer.SetTagged();
// Set document metadata
writer.ViewerPreferences = PdfWriter.DisplayDocTitle;
pdfDoc.AddLanguage("en-US");
pdfDoc.AddTitle("Complaint Intake Form");
writer.CreateXmpMetadata();
pdfDoc.Open();
var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
//tagProcessors.RemoveProcessor(HTML.Tag.IMG);
//tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor());
var cssFiles = new CssFilesImpl();
cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
var cssResolver = new StyleAttrCSSResolver(cssFiles);
var charset = Encoding.UTF8;
var context = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
context.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors);
var htmlPipeline = new HtmlPipeline(context, new PdfWriterPipeline(pdfDoc, writer));
var cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
var worker = new XMLWorker(cssPipeline, true);
var xmlParser = new XMLParser(true, worker, charset);
try
{
using (var sr = new StringReader(htmlContent))
{
xmlParser.Parse(sr);
// xmlParser.Flush();
}
}
catch (Exception e)
{
Response.Write(e.Message);
}
pdfDoc.Close();
//writer.Close();
///this creates a pdf download.
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.OutputStream.Write(memStream.GetBuffer(), 0, memStream.GetBuffer().Length);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("The following error occurred:\n" + ex.ToString());
}
}
}
when I add the following to create the file. The file is created but it is corrupted and cannot open as a pdf
using (FileStream file = new FileStream(Server.MapPath("~/tempFiles/") + fileName, FileMode.CreateNew))
{
byte[] bytes = new byte[memStream.Length];
memStream.Read(bytes, 0, memStream.Length);
file.Write(bytes, 0, bytes.Length);
}
I think this answer is relevant:
Copy MemoryStream to FileStream and save the file?
Your two code snippets use both memStream and memString and without seeing all the code in context, I'm guessing. Assuming memStream is a Stream that contains the contents of your PDF, you can write it to a file like this:
using (FileStream file = new FileStream(Server.MapPath("~/tempFiles/") + fileName, FileMode.CreateNew))
{
memStream.Position = 0;
memStream.CopyTo(file);
}
I wound up moving the new FileStream call into the PdfWriter.GetInstance method in place of the memStream variable. And was able to get rid of the using filestream code all together.
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath(path)+"/" + fileName, FileMode.CreateNew));
In my controller I want to create a pdf, save it and know only if there are errors, I don't want to get the file to download
public ActionResult CreatePdf(string IDUser, int IDCourse)
{
try
{
string path = Server.MapPath("~/Public/Pdf/");
var fileName = Guid.NewGuid().ToString();
Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 15);
pdfDoc.SetPageSize(PageSize.A4.Rotate());
var pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
var fileStream = new FileStream(Path.Combine(path, fileName), FileMode.Create);
pdfWriter = PdfWriter.GetInstance(pdfDoc, fileStream);
pdfDoc.Open();
...
pdfWriter.CloseStream = false;
pdfDoc.Close();
pdfWriter.Close();
fileStream.Close();
db.SaveChanges();
//Response.Buffer = true;
//Response.ContentType = "application/pdf";
//Response.AddHeader("content-disposition", "attachment;filename=\"" + fileName + "\"");
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.Write(pdfDoc);
//Response.End();
//return File(Response.OutputStream, "application/pdf", fileName.ToString()); // if I want download
return Content("ok");
catch (Exception ex)
{
return Content("error");
}
}
At the beginning I did download the pdf, now I call this procedure in a loop to create more pdfs, so I just want to know if there are errors in the creation.
From the view I call in ajax (jquery) this controller
public ActionResult Create(string listIDUser, int IDCourse)
{
string msg = string.Empty;
try
{
var IDUser = listIDUser.Split(',');
foreach (var item in IDUser)
{
var pdf= CreatePdf(item, IDCourse);
if (pdf!= null)
{
...
}
else
{
return new JsonResult() { Data = new { result = "err", msg = "..." + item } };
}
}
return new JsonResult() { Data = new { result = "ok", msg = "Perfect!" } };
}
catch (Exception ex)
{
return new JsonResult() { Data = new { result = "err", msg = ex.Message } };
}
}
that makes cycles and calls the CreatePdf controller but in the browser with firebug the pdf file returns and not an answer in json as I expect!
Thanks
i am using iTextSharp to create pdf from HTML using external css files. My code is:
string filepath = _configuration["RepositoryPath"];
FileName = FileName + ".pdf";
filepath = filepath + "\\" + FileName;
FileStream mFileStream = null;
PdfWriter pdfWr = null;
Document pdfDoc = null;
MyEvent myEvent = null;
try
{
_log.WriteLogMessage("Request for Create PDF File: " + filepath);
using (pdfDoc = new Document(PageSize))
{
if (PageMargin > 0)
pdfDoc.SetMargins(PageMargin, PageMargin, PageMargin, 0);
if (File.Exists(filepath))
File.Delete(filepath);
mFileStream = new FileStream(filepath, System.IO.FileMode.Create);
pdfWr = PdfWriter.GetInstance(pdfDoc, mFileStream);
myEvent = new MyEvent(Content, PageBorder);
pdfWr.PageEvent = myEvent;
pdfDoc.Open();
pdfDoc.NewPage();
var htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
if (CssFiles != null)
foreach (var item in CssFiles)
{
cssResolver.AddCssFile(item, true);
}
var pipeline = new CssResolverPipeline(cssResolver,
new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, pdfWr)));
var worker = new XMLWorker(pipeline, true);
var parser = new XMLParser(worker);
for (int contentCount = 0; contentCount < Content.Length; contentCount++)
{
if (!String.IsNullOrEmpty(Content[contentCount].ToString()))
{
Content[contentCount] = Content[contentCount].Replace("<br>", "<br />").Replace("\r", "").Replace("\n", "");
}
using (var sr = new StringReader(Content[contentCount].ToString()))
{
parser.Parse(sr);//Exception occurs
}
if (contentCount != Content.Length - 1)
pdfDoc.NewPage();
}
}
if (PageSizeType == "BOOKLET")
{
manipulatePdf(filepath, filepath.Replace(".pdf", "_booklet.pdf"));
}
}
catch (Exception ex)
{
_log.WriteLogException(ex);
}
finally
{
pdfDoc.Close();
mFileStream.Close();
}
But i am getting exception
Exception thrown: 'System.MissingMethodException' in
itextsharp.xmlworker.dll Exception thrown: 'System.IO.IOException' in
itextsharp.dll
Please help me where i am doing wrong.
I'm generating a PDF document based on template. The document has multiple pages. The document can have about 5000 pages. When creating the 500-th page I get an overflow RAM (memory). Any idea?
public static void CreateBankBlank2012Year(string pdfTemplatePath, string directoryOutPdf, string nameOutPdf, AnnualReportsFilterParameters filterParametrs, string serverPath)
{
// Get details salary
IEnumerable<SalayDetailsForPdf> dataSalaryDetails = (IEnumerable<SalayDetailsForPdf>) GetSalaryData(filterParametrs);
String fontPath = Path.Combine(serverPath + "\\Fonts", "STSONG.ttf");
Font font = FontFactory.GetFont(fontPath, BaseFont.IDENTITY_H, 8);
using (Document document = new Document())
{
using (PdfSmartCopy copy = new PdfSmartCopy(
document, new FileStream(directoryOutPdf + nameOutPdf, FileMode.Create))
)
{
document.Open();
foreach (var data in dataSalaryDetails)
{
PdfReader reader = new PdfReader(pdfTemplatePath + #"\EmptyTemplateBankBlank_2012.pdf");
using (var ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
stamper.AcroFields.AddSubstitutionFont(font.BaseFont);
AcroFields form = stamper.AcroFields;
form.SetField("t1_address1", data.Address1);
form.SetField("t1_name", data.NameHieroglyphic);
// Other field ...
stamper.FormFlattening = true;
}
reader = new PdfReader(ms.ToArray());
copy.AddPage(copy.GetImportedPage(reader, 1));
}
}
}
}
}
p.s
I'm trying resolve my problem as follow:
generating empty pages based on template
private static void GeneratePdfFromTemplate(string directoryOutPdf, string nameOutPdf, string pdfTemplatePath, int countPages)
{
using (Document document = new Document())
{
using (PdfSmartCopy copy = new PdfSmartCopy(
document, new FileStream(directoryOutPdf + nameOutPdf, FileMode.Create))
)
{
document.Open();
PdfReader reader = new PdfReader(pdfTemplatePath + #"\EmptyTemplateBankBlank_2012.pdf");
for (int i = 0; i < countPages; i++)
{
copy.AddPage(copy.GetImportedPage(reader, 1));
}
reader.Close();
copy.Close();
}
document.Close();
}
GC.Collect();
}
But after a generating I can't set values to the fields.
I'm found solution for my problem, if anyone else would be interested :
private static void SettingFieltValue(Font font, IEnumerable<SalayDetailsForPdf> dataSalaryDetails, int selectedYear, string directoryOutPdf, string nameOutPdf, string pdfTemplatePath)
{
string pdfTemplate = pdfTemplatePath + #"\EmptyTemplateBankBlank_2012.pdf";
string newFile = directoryOutPdf + nameOutPdf;
var fs = new FileStream(newFile, FileMode.Create);
var conc = new PdfConcatenate(fs, true);
foreach (var data in dataSalaryDetails)
{
var reader = new PdfReader(pdfTemplate);
using (var ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
stamper.AcroFields.AddSubstitutionFont(font.BaseFont);
AcroFields form = stamper.AcroFields;
form.SetField("t1_name", data.NameHieroglyphic);
//Other field
stamper.FormFlattening = true;
stamper.Close();
}
reader = new PdfReader(ms.ToArray());
ms.Close();
}
conc.AddPages(reader);
reader.Close();
}
conc.Close();
}