【问题标题】:Add javascript to pdf file using iTextSharp使用 iTextSharp 将 javascript 添加到 pdf 文件
【发布时间】:2015-05-07 09:49:22
【问题描述】:

我想在 pdf 文件中嵌入一个 javascript sn-p,以便在从浏览器窗口打开它时立即打印。为了尝试实现这一点,我正在关注这个例子here.

我创建了一个辅助类,它有一个静态方法来处理这个任务。我已经准备好将 pdf 文件路径字符串传递给该方法。我不明白的是它的输出流部分是如何工作的。我希望将更新的 pdf 保存到我的服务器硬盘上。我不想将它流式传输回我的浏览器。任何指导将不胜感激。

public class PdfHelper
{
    public static void AddPrintFunction(string pdfPath, Stream outputStream)
    {
        PdfReader reader = new PdfReader(pdfPath);
        int pageCount = reader.NumberOfPages;
        Rectangle pageSize = reader.GetPageSize(1);

        // Set up Writer 
        PdfDocument document = new PdfDocument();

        PdfWriter writer = PdfWriter.GetInstance(document, outputStream);

        document.Open();

        //Copy each page 
        PdfContentByte content = writer.DirectContent;

        for (int i = 0; i < pageCount; i++)
        {
            document.NewPage();
            // page numbers are one based 
            PdfImportedPage page = writer.GetImportedPage(reader, i + 1);
            // x and y correspond to position on the page 
            content.AddTemplate(page, 0, 0);
        }

        // Inert Javascript to print the document after a fraction of a second to allow time to become visible.
        string jsText = "var res = app.setTimeOut(‘var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);’, 200);";

        //string jsTextNoWait = “var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);”;
        PdfAction js = PdfAction.JavaScript(jsText, writer);
        writer.AddJavaScript(js);

        document.Close();

    }
} 

【问题讨论】:

  • 叹息。谁向您展示了如何使用 PdfWriter 和所有这些 getImportedPage 调用来操作现有文档?为什么不简单地使用 PdfStamper?
  • 我以这个链接上的代码为例,虽然它已经很老了。似乎很难找到 itextsharp 的文档。 endlessobsession.com/blog/…
  • 嗯,正如那篇博客的作者所说,“代码可能有点粗糙。它是一种有效的代码,但还没有被完全理解”......

标签: javascript c# pdf itextsharp


【解决方案1】:

关于如何完成此任务,请查看thisthis SO 帖子。

基本上你应该有这样的东西:

var pdfLocalFilePath = Server.MapPath("~/sourceFile.pdf");
var outputLocalFilePath = Server.MapPath("~/outputFile.pdf");
using (var outputStream = new FileStream(outputLocalFilePath, FileMode.CreateNew))
{
    AddPrintFunction(pdfLocalFilePath, outputStream);
    outputStream.Flush();
} 

【讨论】:

  • 此代码不在网络应用程序中,而是在我服务器上的网络 API 控制器中,因此;我无法使用 Server.MapPath()。
  • @Stavros_S,如果您使用的是 ASP.NET 的 Web API,那么 HttpContext.Current.Server.MapPath 确实存在...这是一个如何上传文件的示例(以及也将其本地存储在 Web 服务器上)使用 ASP.NET 的 Web API:asp.net/web-api/overview/advanced/…
  • 致对我的评论/帖子投了反对票的读者 - 如果您想多解释一下为什么您不同意我所说的话,我将不胜感激...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 2010-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多