我正在使用 pdfkit 库将 Html 转换为 pdf 并在转换 pdf 后将其转换为 base64(String) 并将其作为 API 响应发送。在前端 (React) 收到 base64(String) 并使用 base64(String) 创建一个元素以下载为 pdf。但是下载pdf后,所有图像都会变得模糊。
Html 到 Pdf 转换器 ApiClass:
class BasicTutorCVPDF(Resource):
@staticmethod
@is_user_authenticate()
def get(_id):
try:
context = TutorModel.profile_info(_id)
html = render_template("tutorCVPDF.html", context=context)
options = {
'page-size': 'A4',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
}
pdfkit.from_string(html, 'public/pdf/tutor_cv.pdf', options=options)
with open("public/pdf/tutor_cv.pdf", "rb") as file:
encode_string = base64.b64encode(file.read())
data = str(encode_string).split("'")[1]
return (ResService.success(None, data), ResService.success(None, data)['status']) if data else \
(ResService.not_acceptable(), ResService.not_acceptable()['status'])
except Exception as err:
LOG.report(err)
return ResService.bad_request(), ResService.bad_request()['status']
html模板:
<tr>
<td style="text-align: left; width: 280px;">Tutor ID : </td>
<td>{{ context['user_info']['id'] }}</td>
<td rowspan="5" style="text-align: right;"><img src="{{ context['user_info']['photo'] }}" style="height: 160px; width: 160px;" alt=""></td>
</tr>
在前端接收 Base64(String):
export const fetchTutorCVPDF = (tutorId) => dispatch => {
req.getRequest({
url: Constants.STATIC + 'tutor-cv-pdf/' + tutorId, auth: 'bearer', }, (cb) => {
const linkSource = `data:application/pdf;base64,${cb}`;
const downloadLink = document.createElement("a");
const fileName = "cv_" + tutorId + ".pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
})
};
下载的PDF: