Django JSignature Templated Docs
Я использую Django 4.1.3, templated_docs и Jsignature. Я надеюсь, что смогу поместить изображение подписи, сгенерированное jsignature, непосредственно в документ.
Я пробовал почти все комбинации использования Draw_signature, templated_docs {% image %}, и даже {{form.media}} {{form.field}}, отмеченные в Jsignature.
любое понимание здесь будет полезно.
from templated_docs import fill_template
from templated_docs.http import FileResponse
from django.http import HttpResponseNotFound
from invoiceManager.models import Invoice
from jsignature.utils import draw_signature
def invoice_view(request, **kwargs):
pk = kwargs.get('pk', None)
if pk:
# try:
invoice = Invoice.objects.get(pk=pk)
information = {
'repairDate': invoice.repair_date,
'claim': invoice.claim_authorization_number,
'customerName': invoice.customer.name,
'customerAddress': invoice.customer.address,
'customerCityStateZip': f'{invoice.customer.city} {invoice.customer.state.abbreviation}, {invoice.customer.zip_code}',
'customerPhone': invoice.customer.phone_number,
'insuranceName': invoice.insurance.name,
'policyNumber': f'policy Number: {invoice.policy_number}',
'VIN': f'VIN: {invoice.vehicle_information.vin}',
'YMM': f'{invoice.vehicle_information.year} {invoice.vehicle_information.make} {invoice.vehicle_information.model}',
'customerSignature': draw_signature(invoice.signature),
'technician': invoice.technician.name,
'location': invoice.business_location.name,
'submissionDate': invoice.invoice_submission_date,
'amount':invoice.invoice_amount,
}
repairLocations = {f'RL{x}':"Repair Made" for x in invoice.location_of_repairs.all().values_list('id', flat=True).order_by().distinct()}
information.update(repairLocations)
filename = fill_template(
'docs/base_invoice.odt', information,
output_format=".pdf")
visible_filename = 'invoice{}'.format(".pdf")
return FileResponse(filename, visible_filename)
Я переписал тег image, чтобы он принимал путь, позволяющий использовать jsignature.draw_siganture(, as_file=True). Создается временный файл, на который может ссылаться PIL, а затем перерисовываться - менее чем идеально, но позволяет сохранить соотношение сторон/размер поля jsignature.
from PIL import Image
from django.utils.html import escape
from django import template
register = template.Library()
PIXEL_TO_CM = 0.00846666
class ImageNode(template.Node):
def __init__(self, value):
self.value = template.Variable(value)
def render(self, context):
self.value = self.value.resolve(context)
images = context.dicts[0].setdefault('ootemplate_imgs', {})
id = len(images)
z_index = id + 3 # Magic
photo = Image.open(self.value)
width = photo.size[0] * PIXEL_TO_CM
height = photo.size[0] * PIXEL_TO_CM
return ('<draw:frame draw:style-name="gr%(z_index)s" '
'draw:name="Signature" '
'text:anchor-type="char" svg:width="%(width)fcm" '
'svg:height="%(height)fcm" draw:z-index="%(z_index)s">'
f'<draw:image xlink:href="{self.value}" '
'xlink:type="simple" xlink:show="embed" '
'xlink:actuate="onLoad"/></draw:frame>') % locals()
@register.tag
def template_image(parser, token):
_, path = token.split_contents()
return ImageNode(path)