問題描述

我使用 wkhtmltopdf 轉換為 PDF 格式的 HTML 文件; 它給出了令人驚訝的好結果,正如 WebKit 所做的一樣。

我使用 Google Web Fonts 給用户定製其編輯的文檔的外觀的可能性,為他們提供了選擇幾種字體的可能性。它也可以在瀏覽器中完美地工作。

問題是,當使用 wkhtmltopdf 將此類 HTML 文件轉換為 PDF 時,我無法使 Google 字體正常工作。我讀了其他人都有相同的 issue

有人可以幫我解決這個問題嗎?

編輯:直接在 CSS 中聲明 @ font-face 也不起作用。

最佳解決方案

要通過 wkhtmltopdf 將 HTML 轉換為 PDF,儘量避免使用 woff 字體。使用 Google Web Fontstruetype 格式與 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

我已經使用 pdfkitwicked_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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇