python 富文本编辑器内容导出为pdf
将富文本内容导出为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)
```