想要把VisualForce Page轉換成PDF隻需要在<apex:page>加上renderAs="pdf"
<apex:page renderAs="pdf">
然後可以通過一些CSS來控制一些列印時的設定
具體的CSS轉換PDF的用法,可以參照這個連結: http://www.antennahouse.com/CSSInfo/CSS-Page-Tutorial-en.pdf
下面這段代碼要建立這樣的一個PDF
- 使用A4 橫版作為Page size
- 有25mm的Margin
- 每一頁有頁眉和頁腳
- 每一個Div自己一頁
<apex:page renderAs="pdf" applyBodyTag="false">
<head>
<style>
@page {
size: A4 landscape;
margin: 25mm;
@top-center {
content: "Sample of Print PDF";
}
@bottom-center {
content: "Page " counter(page) " of " counter(pages);
}
}
.page-break {
display:block;
page-break-after:always;
}
body {
font-family: Arial Unicode MS;
}
.companyName {
font: bold 30px;
color: red;
}
</style>
</head>
<body>
<div class="page-break" align="center">
<h1>Page A</h1>
<apex:panelGrid columns="1" width="100%">
<apex:outputText styleClass="companyName" value="My Company"/>
<apex:outputText value="{!NOW()}"/>
</apex:panelGrid>
</div>
<div class="page-break">Page B</div>
<div>Page C</div>
</body>
</apex:page>
這裡有幾點要注意
- <style>不是一個VF的标簽,是以必須放在<Head>裡面,否者不會被解析
- applyBodyTag="false" 是來設定是否允許VF在Render這個頁面的時候,自動配置設定body标簽,如果允許VF自動設定,分頁等一些CSS顯示的都會不正确
- <apex:panelGrid>實際上對應的是HTML的Table标簽,是以記得要設定寬度和列數,不然的話,無法按照預期的模式來對齊。
效果如下:
另外還有一些在你使用renderAs的時候要注意的事情
- renderAs隻支援PDF
- 一些标準的components和一些form标簽,如input、buttons,或者一些需要javascript來呈現的标簽,并不容易被render,是以慎用
- 不是所有的Page都可以随便的用renderAs,這個隻适用于特意為PDF設計和優化過的VF。
- 如果你的内容是通過JS畫出來的,PDF不支援
- 如果PDF無法正确的顯示雙位元組的内容,可以試着調整CSS的字型
<apex:page showHeader="false" applyBodyTag="false" renderAs="pdf">
<head>
<style>
body { font-family: 'Arial Unicode MS'; }
</style>
</head>
<body>
これはサンプルページです。<br/>
This is a sample page: API version 28.0
</body>
</apex:page>
一些Size的限制
- The maximum response size when creating a PDF must be below 15 MB before being rendered as a PDF. This is the standard limit for all Visualforce requests.
- The maximum file size for a generated PDF is 60 MB.
- The maximum total size of all images included in a generated PDF is 30 MB.
- PDF rendering doesn’t support images encoded in the data: URI scheme format.
- Note that the following components do not support double-byte fonts when rendered as a PDF:
- <apex:pageBlock>
- <apex:sectionHeader>
相關URL
http://www.salesforce.com/us/developer/docs/pages/Content/pages_quick_start_renderas_pdf.htm
http://www.salesforce.com/us/developer/docs/pages/Content/pages_compref_additional_render_pdf.htm