如何使用itext7在内存流而不是物理文件中创建PDF? 我不知道如何在最新版本中做任何帮助?
我尝试了以下代码,但pdfSM未正确填充:
string filePath = "./abc.pdf";
MemoryStream pdfSM = new ByteArrayOutputStream();
PdfDocument doc = new PdfDocument(new PdfReader(filePath), new PdfWriter(pdfSM));
.......
doc.close();
以下完整的测试代码供您参考,它在将文件路径传递到PdfWriter时工作,但不适用于内存流:
public static readonly String sourceFolder = "../../FormTest/";
public static readonly String destinationFolder = "../../Output/";
static void Main(string[] args)
{
String srcFilePattern = "I-983";
String destPattern = "I-129_2014_";
String src = sourceFolder + srcFilePattern + ".pdf";
String dest = destinationFolder + destPattern + "_flattened.pdf";
MemoryStream returnSM = new MemoryStream();
PdfDocument doc = new PdfDocument(new PdfReader(src), new PdfWriter(returnSM));
PdfAcroForm form = PdfAcroForm.GetAcroForm(doc, false);
foreach (PdfFormField field in form.GetFormFields().Values)
{
var fieldName = field.GetFieldName();
var type = field.GetType();
if (fieldName != null)
{
if (type.Name.Equals("PdfTextFormField"))
{
field.SetValue("T");
}
}
}
form.FlattenFields();
doc.Close();
}
答案 0 :(得分:4)
这适合我。
public byte[] CreatePdf()
{
var stream = new MemoryStream();
var writer = new PdfWriter(stream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello world!"));
document.Close();
return stream.ToArray();
}
答案 1 :(得分:1)
iText7,C#控制器
错误:
public ActionResult Report()
{
//...
doc1.Close();
return File(memoryStream1, "application/pdf", "pdf_file_name.pdf");
}
工作:
public ActionResult Report()
{
//...
doc1.Close();
byte[] byte1 = memoryStream1.ToArray();
return File(byte1, "application/pdf", "pdf_file_name.pdf");
}
我不知道为什么...但是,它在起作用!
另一个:link
答案 2 :(得分:1)
我需要同样的东西。像这样工作:
string HtmlString = "<html><head></head><body>some content</body></html>";
byte[] buffer;
using (MemoryStream memStream = new MemoryStream())
{
ConverterProperties props = new ConverterProperties();
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(memStream));
pdfDoc.SetDefaultPageSize(PageSize.LETTER);
HtmlConverter.ConvertToPdf(HtmlString, pdfDoc, props);
pdfDoc.Close();
buffer = memStream.ToArray();
}
return buffer;
C#8“使用”语句替代:
using MemoryStream memStream = new MemoryStream();
ConverterProperties props = new ConverterProperties();
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(memStream));
pdfDoc.SetDefaultPageSize(PageSize.LETTER);
HtmlConverter.ConvertToPdf(reader, pdfDoc, props);
pdfDoc.Close();
buffer = memStream.ToArray();