我发布了一个较早的问题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函数(.js文件的文件名)中包含
includeScript("pdfOut.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为
mainOrder_CA
的按钮,我想将元素test.pdf
(为div)打印为pdf文件名printPdf_CA
。但这行不通。什么都不会发出,也没有任何错误消息。我的应用仍然照常运行。我对JS的知识为零。关于如何修改该代码的任何建议?基本上,我希望在用户单击
div
时将actionButton
元素打印为pdf这是JS代码here的原始帖子
最佳答案
您必须加载JS库jsPDF
和dom-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")
关于javascript - 光泽应用程序是否有“将页面另存为PDF”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59589417/