Coverage for src/backend/InvenTree/plugin/builtin/labels/inventree_label.py: 40%
42 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-07 17:47 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-10-07 17:47 +0000
1"""Default label printing plugin (supports PDF generation)."""
3import io
5from django.core.files.base import ContentFile
6from django.utils.translation import gettext_lazy as _
8from pypdf import PdfWriter
10from InvenTree.helpers import str2bool
11from plugin import InvenTreePlugin
12from plugin.mixins import LabelPrintingMixin, SettingsMixin
15class InvenTreeLabelPlugin(LabelPrintingMixin, SettingsMixin, InvenTreePlugin):
16 """Builtin plugin for label printing.
18 This plugin merges the selected labels into a single PDF file,
19 which is made available for download.
20 """
22 NAME = 'InvenTreeLabel'
23 SLUG = 'inventreelabel'
24 TITLE = _('InvenTree PDF label printer')
25 DESCRIPTION = _('Provides native support for printing PDF labels')
26 VERSION = '1.1.0'
27 AUTHOR = _('InvenTree contributors')
29 BLOCKING_PRINT = True
31 SETTINGS = {
32 'DEBUG': {
33 'name': _('Debug mode'),
34 'description': _('Enable debug mode - returns raw HTML instead of PDF'),
35 'validator': bool,
36 'default': False,
37 }
38 }
40 # Keep track of individual label outputs
41 # These will be stitched together at the end of printing
42 outputs = []
44 def before_printing(self):
45 """Reset the list of label outputs."""
46 self.outputs = []
48 def print_label(self, **kwargs):
49 """Print a single label."""
50 label = kwargs['label_instance']
51 instance = kwargs['item_instance']
53 if str2bool(self.get_setting('DEBUG')):
54 # In debug mode, return raw HTML output
55 output = self.render_to_html(label, instance, None, **kwargs)
56 else:
57 # Output is already provided
58 output = kwargs.get('pdf_data')
60 self.outputs.append(output)
62 def get_generated_file(self, **kwargs):
63 """Return the generated file, by stitching together the individual label outputs."""
64 if len(self.outputs) == 0:
65 return None
67 if str2bool(self.get_setting('DEBUG')):
68 # Simple HTML output
69 data = '\n'.join(self.outputs)
70 filename = 'labels.html'
71 else:
72 # Stitch together the PDF outputs
73 pdf_writer = PdfWriter()
75 for output in self.outputs:
76 output_file = io.BytesIO(output)
77 pdf_writer.append(output_file)
79 pdf_file = io.BytesIO()
80 pdf_writer.write(pdf_file)
81 data = pdf_file.getvalue()
82 pdf_file.close()
84 filename = kwargs.get('filename', 'labels.pdf')
86 return ContentFile(data, name=filename)