我有一个 c# 类,它接受 HTML 并使用 wkhtmltopdf 将其转换为 PDF。
正如您将在下面看到的,我生成了 3 个 PDF - 横向、纵向以及两者的组合。
该properties对象包含字符串形式的 html 以及横向/纵向的参数。
System.IO.MemoryStream PDF = new WkHtmlToPdfConverter().GetPdfStream(properties);
System.IO.FileStream file = new System.IO.FileStream("abc_landscape.pdf", System.IO.FileMode.Create);
PDF.Position = 0;
properties.IsHorizontalOrientation = false;
System.IO.MemoryStream PDF_portrait = new WkHtmlToPdfConverter().GetPdfStream(properties);
System.IO.FileStream file_portrait = new System.IO.FileStream("abc_portrait.pdf", System.IO.FileMode.Create);
PDF_portrait.Position = 0;
System.IO.MemoryStream finalStream = new System.IO.MemoryStream();
PDF.CopyTo(finalStream);
PDF_portrait.CopyTo(finalStream);
System.IO.FileStream file_combined = new System.IO.FileStream("abc_combined.pdf", System.IO.FileMode.Create);
try
{
PDF.WriteTo(file);
PDF.Flush();
PDF_portrait.WriteTo(file_portrait);
PDF_portrait.Flush();
finalStream.WriteTo(file_combined);
finalStream.Flush();
}
catch (Exception)
{
throw;
}
finally
{
PDF.Close();
file.Close();
PDF_portrait.Close();
file_portrait.Close();
finalStream.Close();
file_combined.Close();
}
PDF“abc_landscape.pdf”和“abc_portrait.pdf”按预期正确生成,但当我尝试将两者合并到第三个 pdf (abc_combined.pdf) 中时,操作失败。
我用来MemoryStream执行合并,在调试时,我可以看到finalStream.length等于前两个 PDF 的总和。但当我尝试打开 PDF 时,我只看到两个 PDF 中的 1 个的内容。
下图也可以看到同样的情况:
此外,当我尝试关闭“abc_combined.pdf”时,系统会提示我保存它,而其他 2 个 PDF 则不会出现这种情况。
以下是我已经尝试过的一些方法,但没有效果:
将 CopyTo() 更改为 WriteTo()
将相同的 PDF(横向或纵向)与其自身合并
如果需要,下面是该GetPdfStream()
方法的详细说明。
var htmlStream = new MemoryStream();
var writer = new StreamWriter(htmlStream);
writer.Write(htmlString);
writer.Flush();
htmlStream.Position = 0;
return htmlStream;
Process process = Process.Start(psi);
process.EnableRaisingEvents = true;
函数式编程
千巷猫影
噜噜哒
摇曳的蔷薇
相关分类