2015-12-08 87 views
0

我嘗試將html轉換爲pdf。我使用xhtml2pdf。 我的代碼:創建xhtml2pdf,西里爾字符不起作用

# -*- coding: utf-8 -*- 
from xhtml2pdf import pisa 
sourceHtml = '<html>' \ 
      ' <head>' \ 
      '  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">' \ 
      ' </head>' \ 
      ' <body>' \ 
      '  <p>Русский текст</p>' \ 
      ' </body>' \ 
      '</html>' 

outputFilename = "test.pdf" 

def convertHtmlToPdf(sourceHtml, outputFilename): 
    resultFile = open(outputFilename, "w+b") 
    pisaStatus = pisa.CreatePDF(sourceHtml, dest=resultFile)#, encoding='UTF-8') 
    resultFile.close() 
    return pisaStatus.err 

if __name__ == "__main__": 
    pisa.showLogging() 
    convertHtmlToPdf(sourceHtml, outputFilename) 

PDF,但西里爾字符由黑色方塊表示。 我做錯了什麼?如何使它正確?

回答

1
# -*- coding: utf-8 -*- 
from xhtml2pdf import pisa 
sourceHtml = '<html>' \ 
      ' <head>' \ 
      '  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">' \ 
      '  <style type="text/css">' \ 
      '   @page { size: A4; margin: 1cm; }' \ 
      '   @font-face { font-family: Arial; src: url(/pathToTTF/arial.ttf); }' \ 
      '   p { color: red; font-family: Arial; }' \ 
      '  </style>' \ 
      ' </head>' \ 
      ' <body>' \ 
      '  <p>Русский текст</p>' \ 
      ' </body>' \ 
      '</html>' 

outputFilename = "test.pdf" 

def convertHtmlToPdf(sourceHtml, outputFilename): 
    resultFile = open(outputFilename, "w+b") 
    pisaStatus = pisa.CreatePDF(sourceHtml, dest=resultFile, encoding='UTF-8') 
    resultFile.close() 
    return pisaStatus.err 

if __name__ == "__main__": 
    pisa.showLogging() 
    convertHtmlToPdf(sourceHtml, outputFilename) 

它的工作原理。我不得不將測試樣式設置爲html標籤。

+0

你究竟做了什麼?您只添加了'