python文本编辑器报错_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_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 = '

视频内容地址:%s

' % 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)

```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值