我基于来自 https://github.com/eKoopmans/html2pdf.js/issues/181(odedta)评论的代码,还尝试了他们下面的第二个用户评论。
我有一个使用 html2pdf 包的脚本。效果很好。它创建带有图像的多页 PDF。 PDF 的内容是从 WordPress 类别中提取的数据(使用 wp 查询),并将 3-6 个帖子放入 PDF 中。
HTML 例如:
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<div id="PDFcontent">
<h1> PDF tile </h1>
<img src="https://styles.redditmedia.com/t5_2r5i1/styles/communityIcon_x4lqmqzu1hi81.jpg?width=256&s=fc15e67e2b431bbd2e93e980be3090306b78be55">
<div class="html2pdf__page-break"></div>
<h2 class="exhibitied-title"> Page 2 title<h2>
Some text
<div class="html2pdf__page-break"></div>
<h2> Page 3 title<h2>
Some text
</div>
我的 Jquery 在页面底部
jQuery(function($) {
window.onload = function() {
let el = document.getElementById('PDFcontent');
var title = $('.exhibitied-title').text();
let opt = {
margin: 0.2,
filename: title + '.pdf',
image: {
type: 'jpeg',
quality: 0.99
},
html2canvas: {
scale: 2,
logging: true,
dpi: 192,
letterRendering: true,
/* useCORS: true*/
},
jsPDF: {
unit: 'mm',
format: 'a4',
orientation: 'portrait'
}
};
html2pdf().set(opt).from(el).toPdf().output('datauristring').save().then(function(pdfAsString) {
title = $('.exhibitied-title').text();
filetitle = title + '.pdf';
let data = {
'action': 'send_email_with_pdf',
'fileDataURI': pdfAsString,
'filetitle': filetitle,
}
$.post(myAjax.ajaxurl, data, function(response) {
console.log(response);
});
});
}
});
.save 工作完美,PDF 的格式正是我想要的。
但是在保存或通过电子邮件发送 PDF 时我遇到了问题。 电子邮件已发送并创建 PDF。然而,电子邮件中的 pdf 文件有 115 字节,并且只显示“无法加载 PDF 文档”。当您尝试打开它时,保存在我的 WP 上传文件夹中的 pdf 为 0 字节,并且“无法加载 PDF 文档”。显示。
在我的functions.php中我有
function send_email_with_pdf() {
$pdfdoc = $_POST['fileDataURI'];
$b64file = trim( str_replace( 'data:application/pdf;base64,', '', $pdfdoc ) );
$b64file = str_replace( ' ', '+', $b64file );
$decoded_pdf = base64_decode( $b64file );
//file_put_contents( $attachment, $decodPdf );
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $decoded_pdf );
$filename = $_POST['filetitle'];
if ( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
}
else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents( $file, $image_data );
$mail = new PHPMailer;
$mail->setFrom( '[email protected]', 'My name' );
$mail->addAddress( '[email protected]', 'your name' );
$mail->Subject = 'Subject';
$mail->Body = $filename;
$mail->addStringAttachment($decoded_pdf, $filename);
$mail->isHTML( false );
if( !$mail->send() ) {
$response = 'Message was not sent.';
$response .= 'Mailer error: ' . $mail->ErrorInfo;
}
else {
$response = 'Message has been sent.';
}
wp_send_json( $response );
}
add_action( 'wp_ajax_send_email_with_pdf', 'send_email_with_pdf' );
add_action( 'wp_ajax_nopriv_send_email_with_pdf', 'send_email_with_pdf' );
有人能指出我正确的方向吗?或者有人以前遇到过这个问题吗?
我已发布尽可能多的信息,但如果您需要更多信息,请告诉我。
我已经成功了,供其他需要它的人使用。
我在代码中添加了注释以进行解释
首先将其添加到页面顶部
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
HTML / Wordpress 内容循环部分
<div id="PDFcontent">
<h1 class="mypdftitle"> PDF tile </h1>
<img src="https://styles.redditmedia.com/t5_2r5i1/styles/communityIcon_x4lqmqzu1hi81.jpg?width=256&s=fc15e67e2b431bbd2e93e980be3090306b78be55">
<div class="html2pdf__page-break"></div>
<h2> Page 2 title<h2>
Some text
<div class="html2pdf__page-break"></div>
<h2> Page 3 title<h2>
Some text
</div>
JQuery - 位于页脚上方页面底部
jQuery(function($) {
window.onload = function() {
let el = document.getElementById('PDFcontent');
var title = $('.exhibitied-title').text();
let opt = { //Create/design the pdf
margin: 0.2,
filename: title + '.pdf',
image: {
type: 'jpeg',
quality: 0.99
},
html2canvas: {
scale: 2,
logging: true,
dpi: 192,
letterRendering: true,
},
jsPDF: {
unit: 'mm',
format: 'a4',
orientation: 'portrait'
}
};
html2pdf().from(el).set(opt).toPdf() /*add .save() if you need it to download locally too*/.output('datauristring').then(function(res) {
this.blobString = res;
title = $('mypdftitle').text(); //Get the title from h1 html
filetitle = title; //set the title to be send in the ajax
let data = {
'action': 'send_email_with_pdf', //Name of function in functions.php
'fileDataURI': this.blobString,
'filetitle': filetitle, //name of pdf - you set this above
}
$.post(myAjax.ajaxurl, data, function(response) { //myAjax.ajaxurl see the bottom code comment
console.log(response);
console.log(filetitle);
});
console.log(this.blobString);
});
}
});
```
现在在functions.php中
function send_email_with_pdf() {
if (isset($_POST['fileDataURI'])) {
/*** Prepare and decode the uri string ***/
$pdfdoc = $_POST['fileDataURI']; // This looks like data:application/pdf;filename=generated.pdf;base64,JVBERi0xLjMKJbrfrOAKMyAwIG9iago8PC9UeXB....
$b64file = str_replace( 'data:application/pdf;filename=generated.pdf;base64,', '', $pdfdoc ) ; //remove data:application/pdf;filename=generated.pdf;base64,
$decoded_pdf = base64_decode( $b64file ); //decode it
/**** Unique naming ****/
$date = date("d-m-y"); // Today date day month year
$time = date("h:i"); // The time
//Adding date and time to the pdf, will make sure each pdf generated is unique
$ext = ".pdf"; //file extension
$thename = $_POST['filetitle']; //The title sent by ajax from the extension page
$name = str_replace( ' ', '-', $thename ) ; //remove spaces - makes urls better
$filename = $name . '-' . $date . '-' . $time . $ext; // combine the file name
//If you dont want date and time, then do the following $filename = $thename . $ext;
/**** Upload directory *****/
$upload_dir = wp_upload_dir();
if (wp_mkdir_p($upload_dir['path'])) { // Puts the file in wp-content/uploads/year/month
$file = $upload_dir['path'].
'/'.$filename;
} else {
$file = $upload_dir['basedir'].
'/'.$filename;
}
/*** Upload it ****/
file_put_contents($file, $decoded_pdf);
/*** Send the email ****/
$mail = new PHPMailer;
$mail->setFrom( '[email protected]', 'My name' );
$mail->addAddress( '[email protected]', 'your name' );
$mail - > Subject = $filename;
$mail - > Body = $filename; //email text goes here, I have made it the file name for example
$mail - > addStringAttachment($decoded_pdf, $filename);
$mail - > isHTML(false);
if (!$mail - > send()) {
$response = 'Message was not sent.';
$response. = 'Mailer error: '.$mail - > ErrorInfo;
} else {
$response = 'Message has been sent.';
$response = $image_data;
}
wp_send_json($response);
}
}
add_action('wp_ajax_send_email_with_pdf', 'send_email_with_pdf');
add_action('wp_ajax_nopriv_send_email_with_pdf', 'send_email_with_pdf');
对于那些不确定 JQuery 部分中的 myAjax.ajaxurl 的人,请将其添加到 WordPress 主题中的functions.php 的顶部,然后当您想在站点上调用 Ajax 时,您可以使用 myAjax.ajaxurl
add_action( 'init', 'script_enqueuer' );
function script_enqueuer() {
wp_register_script( "liker_script", get_stylesheet_directory_uri().'/js/functionality.js', array('jquery') );
wp_localize_script( 'liker_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'liker_script' );
}