14

我想将我的 CFM 页面生成的 HTML 转换为 PDF,并在导航到我的页面时让用户使用标准的“另存为”提示进行提示。

4

4 回答 4

18

您应该使用 cfdocument 标记(带有 format="PDF")通过将 PDF 放置在您正在生成的页面周围来生成 PDF。您需要指定文件名属性,否则文档将直接流式传输到您的浏览器。

将内容保存为 PDF 后,结合使用 cfheader 和 cfcontent 将 PDF 输出为附件(“另存为”)并将文件添加到响应流中。我还在 cfcontent 标记上添加了 deletefile="Yes" 以保持文件系统中的文件干净。

<cfdocument format="PDF" filename="file.pdf" overwrite="Yes">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>Hello World</title>
</head>
<body>
    Hello World
</body>
</html>
</cfdocument>
<cfheader name="Content-Disposition" value="attachment;filename=file.pdf">
<cfcontent type="application/octet-stream" file="#expandPath('.')#\file.pdf" deletefile="Yes">

顺便说一句:我只是在下面的示例中使用 file.pdf 作为文件名,但您可能希望对文件名使用一些随机或会话生成的字符串,以避免因竞争条件导致的问题。

于 2008-09-16T16:43:10.407 回答
4

如果您想完全避免存储 PDF,使用不带文件名的 cfdocument 将直接将 pdf(Flashpaper)发送到浏览器,而不使用 cfheader 和 cfcontent。

警告:与使用 cfheader/cfcontent 一样,您需要在缓存刷新到浏览器之前执行此操作,因为它基本上是在执行相同的操作而无需存储文件。

要获取内容,我可能会使用 cfsavecontent 包裹相同的调用/包含/等。生成页面,但有两个主要例外。cfdocument 似乎与外部样式表存在问题,因此使用包含将样式直接放入文档可能是个好主意。您可以尝试使用 @import 代替 - 它适用于某些人。另外,我会小心与图像的相对链接,因为它们有时会中断。

于 2008-09-16T17:59:32.720 回答
3

The <cfdocument> approach is the sanctioned way to get it done, however it does not offer everything possible in the way of manipulating existing PDF documents. I had a project where I needed to generate coupons based using a pre-designed, print-resolution PDF template. <cfdocument> would have let me approximate the output, but only with bitmap images embedded in HTML. True, I could fake print-resolution by making a large image and scaling it in HTML, but the original was a nice, clean, vector-image file and I wanted to use that instead.

I ended up using a copy of <cfx_pdf> to get the job done. (Developer's Site, CF Tag Store) It's a CF wrapper around a Java PDF library that lets you manipulate existing PDF documents, including filling out PDF forms, setting permissions, merging files, drawing vector graphics, tables, and text, use custom fonts, etc, etc. If you are willing to work with it, you can get some pretty spectacular results.

The one drawback is that it appears the developer has left this product out to pasture for a long time. The developer site is still copyright 2003 and doesn't mention anything past ColdFusion MX 6.1. I ended up having to break some of the encrypted templates in order to fix a couple of bugs and make it work as I needed it to. Nontheless, it is a powerful tool.

于 2008-09-17T22:22:07.900 回答
1

我对 ColdFusion 不是很熟悉,但是您需要做的是在用户请求它为 application/octet-stream 时设置页面的 Content-Type。这将提示他们每次下载。

希望这可以帮助!

于 2008-09-16T16:05:04.803 回答