[英]c# How to return a byte array from pdf using iTextsharp
所有,
我創建了以下方法來獲取具有多個tiff頁面文檔的tiff字節數組
我需要將其轉換為pdf,然后返回一個pdf字節數組
我有這個代碼1的 2個問題- 我想返回一個字節[]。 2 - 生成的pdf重復頁面。
public void convertImage(byte[] documentContent)
{
Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"C:\Data\Output.pdf", FileMode.Create)); --for testing purposes
Bitmap oldImage;
using (var ms = new MemoryStream(documentContent))
{
oldImage = new Bitmap(ms);
}
Size newSize = new Size(1024, 737);
using (Bitmap bmp1 = new Bitmap(oldImage, newSize))
{
int total = oldImage.GetFrameCount(FrameDimension.Page);
document.Open();
PdfContentByte cb = writer.DirectContent;
for (int k = 0; k < total; ++k)
{
bmp1.SelectActiveFrame(FrameDimension.Page, k);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bmp1, ImageFormat.Bmp);
var scaleparcent = 72f / img.DpiX * 100;
img.ScalePercent(scaleparcent);
img.ScaleAbsoluteHeight(document.PageSize.Height);
img.ScaleAbsoluteWidth(document.PageSize.Width);
img.SetAbsolutePosition(0, 0);
cb.AddImage(img);
document.NewPage();
}
}
byte[] bytes = null;
document.Close();
}
有人幫忙嗎?
這是一個基本的例子:
private byte[] CreatePdf()
{
Document document = new Document();
using (MemoryStream ms = new MemoryStream())
{
PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(new Paragraph("Hello World"));
document.Close();
return ms.ToArray();
}
}
它與之前的答案類似,但在答案中並未明確表示在從MemoryStream
獲取字節之前需要Close()
document
實例。 在您的代碼段中,您有:
byte[] bytes = null;
document.Close();
根據之前的答案,您可以將其更改為:
byte[] bytes = ms.ToArray();
document.Close();
這是錯誤的,因為bytes
數組不包含完整的PDF。 在document.Close()
,許多基本數據被寫入輸出流(信息字典,根字典,交叉引用表)。
更新:
在C#中,可以自定義using
如注釋中所示:
private byte[] CreatePdf()
{
using (MemoryStream ms = new MemoryStream())
{
using (Document document = new Document())
{
PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(new Paragraph("Hello World"));
}
return ms.ToArray();
}
}
我關於document
需要關閉才能獲得完整PDF的論點仍然有效: document
實例在return ms.ToArray()
之前由}
隱式關閉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.