【问题标题】:Is there a “Save Page As PDF” for Shiny app?Shiny 应用程序是否有“将页面另存为 PDF”?
【发布时间】:2020-04-22 15:47:15
【问题描述】:

我发布了一个较早的问题here,关于将 Shiny 应用程序的页面打印到 pdf 文件以供进一步使用。

所以我发现这个 Javascript 代码可以将某些 CSS 元素打印到 pdf 中

$('#downloadPDF').click(function () {
    domtoimage.toPng(document.getElementById('content2'))
      .then(function (blob) {
          var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
          pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
          pdf.save("test.pdf");
      });
});

然后我将它放在我的 RShiny 项目文件夹中的 .js 文件中,并在我的 ui 函数中包含 includeScript("pdfOut.js")(即 .js 文件的文件名)。我还将元素的 id 更改为我的应用程序中的 id,如下所示:

$('#printPdf_CA').click(function () {
    domtoimage.toPng(document.getElementById('mainOrder_CA'))
        .then(function (blob) {
            var pdf = new jsPDF('l', 'pt', [$('#mainOrder_CA').width(), $('#mainOrder_CA').height()]);

            pdf.addImage(blob, 'PNG', 0, 0, $('#mainOrder_CA').width(), $('#mainOrder_CA').height());
            pdf.save("test.pdf");

            that.options.api.optionsChanged();
        });
});

基本上,如果应用用户单击 ID 为 printPdf_CA 的按钮,我想将元素 mainOrder_CA(这是一个 div)打印为 pdf 文件名 test.pdf

但它不起作用。什么都没有出来,也没有任何错误消息。我的应用程序仍然照常运行。我对JS的了解为零。关于如何修改该代码的任何建议?基本上,当用户单击actionButton 时,我希望将div 元素打印到pdf 中

这里是JS代码here的原帖


【问题讨论】:

    标签: javascript r shiny


    【解决方案1】:

    你必须加载JS库jsPDFdom-to-image

    library(shiny)
    
    js <- "
    $(document).ready(function(){
      $('#printPdf_CA').click(function () {
        domtoimage.toPng(document.getElementById('mainOrder_CA'))
          .then(function (blob) {
            var pdf = new jsPDF('l', 'pt', [$('#mainOrder_CA').width(), $('#mainOrder_CA').height()]);
            pdf.addImage(blob, 'PNG', 0, 0, $('#mainOrder_CA').width(), $('#mainOrder_CA').height());
            pdf.save('test.pdf');
            // that.options.api.optionsChanged(); what is that?
          });
      });
    });
    "
    
    ui <- fluidPage(
      tags$head(
        tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"),
        tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"),
        tags$script(js)
      ),
      br(),
      actionButton("printPdf_CA", "Print"),
      div(
        id = "mainOrder_CA",
        h3("Click on the button to print me")
      )
    )
    
    server <- function(input, output, session){
    
    }
    
    shinyApp(ui, server)
    

    但是,我们使用此应用程序获得的 pdf 文件并不好,它不尊重 div 的尺寸。我不知道为什么。


    编辑

    嗯,当删除h3 的边距时,这可以正常工作:

    h3(style = "margin:0;", "Click on the button to print me")
    

    【讨论】:

    • 谢谢。这真的有效。这对我来说是一个很好的起点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2016-02-03
    • 2020-09-29
    相关资源
    最近更新 更多