public async Task <IActionResult> saveTestToTemplate([FromBody] TestTemplateReq req) { MemoryStream pdfMemoryStream = templateService.saveDataToTemplate(req); Response.Headers.Add("Content-Disposition", "attachment; filename=" + req.fileCode); return(new FileStreamResult(pdfMemoryStream, "application/octet-stream"));//文件流方式,指定文件流对应的ContenType。 }
public MemoryStream saveDataToTemplate(TestTemplateReq allReq) { MemoryStream resultStream = new MemoryStream(); try { MemoryStream memoryStream = new MemoryStream(); PDFEntityConfig pDFEntity = CommonConstantsUtil.PDFCONFIG[allReq.fileCode]; string path = pDFEntity.filePath; PdfReader reader = new PdfReader(path, null); PdfReader.unethicalreading = true; PdfStamper stamper = new PdfStamper(reader, memoryStream, '\0', false); stamper.Writer.CloseStream = false; AcroFields pdfFormFields = stamper.AcroFields; pdfFormFields.SetField(allReq.fieldName, allReq.fieldValue); stamper.FormFlattening = true; stamper.Writer.CloseStream = false; stamper.Close(); memoryStream.Position = 0; reader.Close(); //You have to rewind the MemoryStream before copying // memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.CopyTo(resultStream); memoryStream.Close(); resultStream.Position = 0; } catch (Exception e) { Console.WriteLine(e.Message); } return(resultStream); }