2012-12-10 3 views
2

pisa 유틸리티에서 html2pdf를 변환하려고합니다. 아래 코드를 확인하십시오. 내가 알 수없는 오류가 발생했습니다.Python에서 xhtml2pdf.pisa를 사용하여 아랍어 페이지로 변환

Traceback (most recent call last): 
    File "dewa.py", line 27, in <module> 
    html = html.encode(enc, 'replace') 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 203: ordinal not in range(128) 

여기에서 코드를 확인하십시오.

from cStringIO import StringIO 
from grab import Grab 
from grab.tools.lxml_tools import drop_node, render_html 
from grab.tools.text import remove_bom 
from lxml import etree 
import grab.error 
import inspect 
import lxml 
import os 
import sys 
import xhtml2pdf.pisa as pisa 

enc = 'utf-8' 
filePath = '~/Desktop/dewa' 
############################## 

g = Grab() 
g.go('http://www.dewa.gov.ae/arabic/aboutus/dewahistory.aspx') 

html = g.response.body 

html = html.replace('bgcolor="EDF389"', 'bgcolor="#EDF389"') 


''' clear page ''' 
html = html.encode(enc, 'replace') 

print html 

f = file(filePath + '.html' , 'wb') 
f.write(html) 
f.flush() 
f.close() 

''' Save PDF ''' 
pdfresult = StringIO() 
pdf = pisa.pisaDocument(StringIO(html), pdfresult, encoding = enc) 
f = file(filePath + '.pdf', 'wb') 
f.write(pdfresult.getvalue()) 
f.flush() 
f.close() 
pdfresult.close() 
+1

스택 오버플로에 ** 바이트를 디코딩 할 수 ** '아스키'코덱에 대한 Google 검색 12K + 결과를 반환합니다. 그걸로 시작하고 싶을지도 모릅니다 ... – dda

답변

2

이 선으로 반환 된 객체의 종류를 확인하는 경우 :

html = g.response.body 

당신이 것을 볼 것이다 하지 유니 코드 개체 : 그래서

print type(html) 
... 
<type 'str'> 

당신이 올 이 줄까지 :

html = html.encode(enc, 'replace') 

이미 인코딩 된 문자열 (오류의 원인)을 다시 인코딩하려고합니다.

는 다음과 같이 당신의 코드를 변경,이 문제를 해결하려면

# decode the dowloaded data 
html = g.response.body.decode(enc) 

# html is now a unicode object 
html = html.replace('bgcolor="EDF389"', 'bgcolor="#EDF389"') 

print html 

# encode as utf-8 before writing to file (no need for 'replace') 
html = html.encode(enc) 
+0

친애하는 ekhumoro. 답변 해주셔서 감사합니다. 내가 제안한대로 스크립트를 수정 한 후에는 저장된 pdf/html 파일을 읽을 수 없습니다. 생성 된 파일을 확인하십시오. – ArunaFromLK

+0

내가 준 코드는 정확하고 인코딩 문제를 다룹니다. 폰트와 다른 문제가 있다고 생각합니다. pdf 파일에서 검은 사각형이 많이 보입니까? 그렇다면 [이 질문] (http://stackoverflow.com/q/4047095/984421)이 도움이 될 수 있습니다. – ekhumoro

+0

친애하는 ekhumoro, thans를 다시합니다. 이제 pdf에서 아랍어 텍스트를 볼 수 있습니다. 그러나 모든 본문은 역순으로되어 있습니다. 어떤 단서? – ArunaFromLK

관련 문제