問題描述
我使用 wkhtmltopdf 轉換為 PDF 格式的 HTML 檔案; 它給出了令人驚訝的好結果,正如 WebKit 所做的一樣。
我使用 Google Web Fonts 給使用者定製其編輯的檔案的外觀的可能性,為他們提供了選擇幾種字型的可能性。它也可以在瀏覽器中完美地工作。
問題是,當使用 wkhtmltopdf 將此類 HTML 檔案轉換為 PDF 時,我無法使 Google 字型正常工作。我讀了其他人都有相同的 issue 。
有人可以幫我解決這個問題嗎?
編輯:直接在 CSS 中宣告 @ font-face 也不起作用。
最佳解決方案
要透過 wkhtmltopdf 將 HTML 轉換為 PDF,儘量避免使用 woff 字型。使用 Google Web Fonts 的 truetype 格式與 base64 編碼。
最近我試圖使用 Google Web 字型的 Google 網路字型。在瀏覽器中,它正確顯示,但在將 HTML 轉換為 PDF 後不會顯示。
在廣泛搜尋網頁後,最後我發現了將字型編碼為 base64 格式的工具,並獲得了 @font-face 的 CSS 。
閱讀解決方案 here 。
次佳解決方案
一個簡單的解決方案:Base64 編碼您的字型並將其嵌入到 CSS 中:
@font-face {
font-family: 'OpenSans';
src: url(data:font/truetype;charset=utf-8;base64,AAEAAAATAQA...
}
FontSquirrel 可以透過他們的 Webfont Generator 的高階選項為您做到這一點; Google 等字型可以編碼 with this tool 。
我已經使用 pdfkit 和 wicked_pdf 這個解決方案,它可以透過 wkhtmltopdf 進行工作,所以我認為這應該與原生的 wkhtmltopdf 一起使用。
第三種解決方案
我遇到了同樣的問題,並透過下載字型並將其從我的 Web 伺服器中的本地檔案執行,並使用該 font-face 宣告解決了它:
@font-face {
font-family: 'PT Sans';
src: url( '/public/inc/fonts/PTS55F-webfont.eot');
src: url( '/public/inc/fonts/PTS55F-webfont.eot?#iefix') format('embedded-opentype'),
url( '/public/inc/fonts/PTS55F-webfont.woff') format('woff'),
url( '/public/inc/fonts/PTS55F-webfont.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
我能在 Font Squirrel 上找到這個字型,但是里程可能會有所不同。
我認為,谷歌的字型會發生什麼,它只是想載入它認為這個瀏覽器想要的格式,對於 WebKit 而言,它是 woff(我相信) 。但是 wkhtmltopdf 不能將 woff 字型嵌入到 PDF 中,因此預設為 sans-serif 。透過宣告所有這些,包含 TrueType 字型,這是 PDF 實際使用的。
另外,您需要在任何 font-family CSS 定義中定義要用作第一個字型的字型,否則 wkhtmltopdf 將忽略它。
第四種方案
我必須嘗試一個 gazillion 變體來獲得這項工作 (從本地) 。我試圖透過 WKHtmlToPdf 將 Open Sans Condensed 嵌入到 pdf 中。
我認為您必須直接從谷歌下載安裝 Open Sans Condensed ttf 並進行安裝。安裝後重新啟動以允許其他服務訪問也很重要。我原來從 font-squirrel 下載 ttf,並在 Windows /Fonts 中列出了”Open Sans”,這是錯誤的,如果你照顧 google 安裝它被列為 「開啟 Sans Condensed Light」,所以即使谷歌的 local('Open Sans Cond Light')指令碼是錯誤的。
如前所述,你需要明確的拉伸和重量,所以這是對我有用的:
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans');
}
@font-face {
font-family: 'Open Sans Condensed';
font-stretch:condensed;
font-style: normal;
font-weight: 300;
src: local('Open Sans Condensed Light');
}
@@font-face { font-family: 'Open Sans Condensed Bold'; font-stretch:condensed; font-style: normal; font-weight: 700; src: local('Open Sans Condensed'), local('Open Sans Condensed Bold');}
第五種方案
我剛剛測試過使用 @import 符號工程:
<style>
@import 'https://googlefonts.admincdn.com/css?family=Montserrat';
</style>
我使用的是 django-wkhtmltopdf 2.0.3 版
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。