将PDF链接为可下载的文档

时间:2010-12-15 作者:Lucy

如何在内容中添加指向PDF的链接,使其下载而不是在浏览器窗口中打开?(我已将PDF上载到媒体库,可以插入链接,但找不到阻止其在浏览器窗口中打开的选项)。

谢谢

露西

4 个回复
SO网友:Sébastien Méric

您可以尝试将此添加到。htaccess:

<FilesMatch "\\.(?i:pdf)$">
    # Force File Download
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</FilesMatch>

SO网友:goldenapples

PDF将以mime类型保存application/pdf, 所以如果你的主题有application.phppdf.php 强制下载的模板文件(或者如果您在attachment.php 模板),您可以强制下载。

A.pdf.php 在主题中这样构建的文件应该可以做到:

<?php  if (have_posts()) : while (have_posts()) : the_post();

$pdf_title = $post->post_title;
$uploads_dir = wp_upload_dir();
$attachment_src = get_post_meta( $post->ID, \'_wp_attached_file\', true );
$pdf_src = path_join( $uploads_dir[\'path\'], $attachment_src );


 header("Pragma: public"); // required
 header("Expires: 0");
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 header("Cache-Control: private",false); // required for certain browsers 
 header("Content-Type: application/pdf");
 header("Content-Disposition: attachment; filename=\\"".$pdf_title."\\";" );
 header("Content-Transfer-Encoding: binary");
 header("Content-Length: ".filesize($pdf_src));
 ob_clean();
 flush();
 readfile("$pdf_src");


endwhile; endif;

?>
(编辑:我应该注意的是,为了让它工作,当你通过媒体上传器将文件插入帖子时,你必须选择Post URL 而不是File URL 在插入帖子之前,请在链接URL字段中。指向文件名的链接将遵循浏览器的首选项,但通过链接到WP post链接,您可以控制其行为。)

SO网友:EAMann

实际上,这完全取决于浏览器。一些浏览器将使用内置PDF阅读器在窗口中打开PDF(大多数浏览器使用Adobe插件,Google Chrome有自己的插件)。但是,如果插件丢失,浏览器将尝试下载该文件。

最安全的方法是在页面上添加说明,让用户右键单击并选择“另存为”

如果您担心用户单击链接后无法返回页面,请添加target="_blank" 它将强制浏览器在新选项卡或窗口中打开链接。有时,这也足以触发下载。

例如:<a href="http://site.url/document.pdf" target="_blank">Download PDF</a>.

SO网友:Dikkie Dik

只需使用a标记的下载属性:https://www.w3schools.com/tags/att_a_download.asp

结束

相关推荐

Stop underlining image links

在我的小部件栏上,我有一个超链接的图像。问题是CSS强调了这一点。如何删除下划线?更新:刚刚注意到这是导致下划线的原因:} .entry a, .secondaryColumn a, #commentsContainer h3 a, .commentlist .comment-author a { border-bottom: 1px solid #ddd; color: #3c6c92; font-weight: bold;