Reprinted from: http://blog.csdn.net/polo_longsan/article/details/39254867
Although this is java, the principle is basically the same
asp.net code is as follows
transfer:
using iTextSharp.text; using iTextSharp.text.pdf;
public void Index() { //Get the Chinese font, the third parameter indicates whether to sneak into the font, but as long as it is an encoded font, it will be embedded. BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); // BaseFont baseFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", // BaseFont.NOT_EMBEDDED); //read template file PdfReader reader = new PdfReader(@"C:\Users\shxy\Desktop\test2.pdf"); //Create a file stream to save the file after filling the template System.IO.MemoryStream stream = new System.IO.MemoryStream(); PdfStamper stamp = new PdfStamper(reader, stream); //Set the form font, it is useful in the high version, if the high version adds this sentence, the font will not be inserted, and the low version is useless stamp.AcroFields.AddSubstitutionFont(baseFont); AcroFields form = stamp.AcroFields; form.SetField("Name", "石义"); form.SetField("test", "Name"); form.SetField("Payment", "1"); form.SetField("test2", "1"); //Whether the form text box is locked stamp.FormFlattening = false; Dictionary<string, string> para = new Dictionary<string, string>(); // para.Add("Name", "abc"); //fill the form, para is a (attribute-value) dictionary of the form //foreach (KeyValuePair<string, string> parameter in para) //{ // //To enter Chinese, you need to set the font of the field; // form.SetFieldProperty(parameter.Key, "textfont", baseFont, null); // //Set the value for the field that needs to be assigned; // form.SetField(parameter.Key, parameter.Value); //} //Close the io stream in order stamp.Close(); reader.Close(); //generate file Response.Clear(); Response.AppendHeader("Content-Disposition", "attachment;filename=pdftest.pdf"); Response.ContentType = "application/octet-stream"; Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length); Response.OutputStream.Flush(); Response.OutputStream.Close(); Response.Flush(); Response.End(); //FileResult fileResult = new FileContentResult(stream.ToArray(), "application/pdf"); //fileResult.FileDownloadName = "4.pdf"; //return fileResult; }
Problems encountered during the process:
The posted code is the Chinese version, don't care, it mainly depends on the font. In the process, the single-selection and multiple-selection of the template are encountered. The incoming parameters need to be determined according to the actual value of your pdf template. It is difficult to guess and estimate.
I am using Adobe Acrobat 9 Pro which has a cracked version online.
The idea after that is to upload a template and match the parameters, so that the template data can be automatically filled and printed by itself.