將富文本內容導出為pdf
1.使用 xhtml2pdf 缺點 遇到樣式問題時會報錯,rgba之類的css問題解決不了
from xhtml2pdf import pisa
class CourseMaterialExportPdfAPIView(generics.GenericAPIView):
permission_classes = (IsAuthenticatedOrHasOpenid,)
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
try:
material = CourseMaterial.objects.get(id=pk)
content = material.content
import re
# 處理視頻內容,因為不能展示視頻,所以將視頻的html代碼轉換為視頻內容和連接
pattern = re.compile(r'<video.*?>')
video_list = pattern.findall(content)
sub_dic = dict()
for video_tem_code in video_list:
res = re.search('src=(.*?) ', video_tem_code)
url = res.group(1)
repl = '<p>視頻內容地址:%s</p>' % url
sub_dic[video_tem_code] = repl
for string, repl in sub_dic.items():
content = content.replace(string, repl)
# 需要安裝xhtml2pdf模塊 pip install
from xhtml2pdf import pisa
# 處理漢字亂碼問題
from xhtml2pdf.default import DEFAULT_FONT
DEFAULT_FONT['helvetica'] = 'yh'
#導出,直接下載pdf
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s.pdf' % material.name
#content為富文本的內容, response為保存生成的pdf的地方
pisa.CreatePDF(StringIO(content), response)
return response
except CourseMaterial.DoesNotExist:
return Response({'status': 0, 'error': '活動不存在'})
- 使用wkhtmltopdf
import pdfkit
html_url = request.GET.get('html_url')
# pdfkit配置
config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf') #wkhtmltopdf的安裝路徑
options = {
'page-size': 'Letter',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'no-outline': None,
'quiet': '',
}
# 生成的pdf存放路徑
pdf_path = '{}.pdf'.format(uuid.uuid4())
# 主題 周計划,日計划導出,復用接口
if html_url:
pdfkit.from_url(html_url, pdf_path, configuration=config, options=options)
file_name = request.GET.get('file_name')
with open(pdf_path)as f:
DEFAULT_FONT['helvetica'] = 'yh'
response = StreamingHttpResponse(f.read(), mimetype="application/pdf")
response['Content-Disposition'] = 'attachment; filename={}.pdf'.format(file_name)
os.remove(pdf_path)
```