fix: possible fix to encoding issues in py3

This commit is contained in:
Shivam Mishra 2019-04-27 17:41:25 +05:30
parent 01a2df7e5a
commit 8e29bc4bf7
2 changed files with 16 additions and 8 deletions

View file

@ -5,8 +5,8 @@ from __future__ import unicode_literals
import unittest
import frappe.utils.pdf as pdfgen
from PyPDF2 import PdfFileReader, PdfFileWriter
import pdfkit, io
import frappe, io, six
from PyPDF2 import PdfFileReader
#class TestPdfBorders(unittest.TestCase):
class TestPdf(unittest.TestCase):
@ -34,13 +34,16 @@ class TestPdf(unittest.TestCase):
self.test_read_options_from_html()
def test_read_options_from_html(self):
html, html_options = pdfgen.read_options_from_html(self.html)
_, html_options = pdfgen.read_options_from_html(self.html)
self.assertTrue(html_options['margin-top'] == '0')
self.assertTrue(html_options['margin-left'] == '10')
self.assertTrue(html_options['margin-right'] == '0')
def test_pdf_encryption(self):
pdf = pdfgen.get_pdf(self.html, options={"password": "qwe"})
password = "qwe"
pdf = pdfgen.get_pdf(self.html, options={"password": password})
reader = PdfFileReader(io.BytesIO(pdf))
self.assertTrue(reader.isEncrypted)
self.assertTrue(reader.decrypt("qwe".encode('utf-8')))
if six.PY2:
password = frappe.safe_encode(password)
self.assertTrue(reader.decrypt(password))

View file

@ -5,9 +5,9 @@ from __future__ import unicode_literals
import pdfkit, os, frappe
from frappe.utils import scrub_urls
from frappe import _
import six, re, io
from bs4 import BeautifulSoup
from PyPDF2 import PdfFileReader, PdfFileWriter
import re, io
def get_pdf(html, options=None, output=None):
html = scrub_urls(html)
@ -42,10 +42,15 @@ def get_pdf(html, options=None, output=None):
else:
raise
password = options["password"]
if six.PY2:
password = frappe.safe_encode(password)
if output:
# Encrypt if required
if "password" in options:
output.encrypt(options["password"].encode('utf-8'))
output.encrypt(password)
return get_file_data_from_writer(output)
writer = PdfFileWriter()
@ -53,7 +58,7 @@ def get_pdf(html, options=None, output=None):
writer.appendPagesFromReader(reader)
if "password" in options:
writer.encrypt(options["password"].encode('utf-8'))
writer.encrypt(password)
filedata = get_file_data_from_writer(writer)