2016-08-11 9 views
2

Reportlab SimpleDocTemplateを使用してpdfファイルを作成しています。私はファイル内の多くの画像を調整できるように、複数の画像を行単位で書き込む必要があります。複数のバーコードを行数で追加するためのReportLab SimpleDocTemplateのアラインメントの適用

class PrintBarCodes(View): 

    def get(self, request, format=None): 
     response = HttpResponse(content_type='application/pdf') 
     response['Content-Disposition'] = 'attachment;\ 
     filename="barcodes.pdf"' 

     # Close the PDF object cleanly, and we're done. 
     ean = barcode.get('ean13', '123456789102', writer=ImageWriter()) 
     filename = ean.save('ean13') 
     doc = SimpleDocTemplate(response, pagesize=A4) 
     parts = [] 
     parts.append(Image(filename)) 
     doc.build(parts) 
     return response 

コードでは、ファイルに1つのバーコードを印刷しました。そして、出力は以下に示すように画像に表示されます。

しかし、私はいくつかのバーコードを描画する必要があります。どのようにPDFファイルに描画し、行の方法で調整する前にイメージのサイズを減らすには?あなたの質問として

enter image description here

+0

あなたの答えは以下の通りですか? – B8vrede

+0

うん。ありがとう@ B8vrede –

答えて

2

あなたは、私が最も賢明なアプローチはFlowable年代を使用していると思わ柔軟性が必要であることを示唆しています。通常バーコードは1つではありませんが、簡単にmake it oneとすることができます。そうすれば、は、バーコードごとにレイアウトにどれくらいのスペースがあるかを決めることができます。

from reportlab.graphics import renderPDF 
from reportlab.graphics.barcode.eanbc import Ean13BarcodeWidget 
from reportlab.graphics.shapes import Drawing 
from reportlab.platypus import Flowable 

class BarCode(Flowable): 
    # Based on https://stackoverflow.com/questions/18569682/use-qrcodewidget-or-plotarea-with-platypus 
    def __init__(self, value="1234567890", ratio=0.5): 
     # init and store rendering value 
     Flowable.__init__(self) 
     self.value = value 
     self.ratio = ratio 

    def wrap(self, availWidth, availHeight): 
     # Make the barcode fill the width while maintaining the ratio 
     self.width = availWidth 
     self.height = self.ratio * availWidth 
     return self.width, self.height 

    def draw(self): 
     # Flowable canvas 
     bar_code = Ean13BarcodeWidget(value=self.value) 
     bounds = bar_code.getBounds() 
     bar_width = bounds[2] - bounds[0] 
     bar_height = bounds[3] - bounds[1] 
     w = float(self.width) 
     h = float(self.height) 
     d = Drawing(w, h, transform=[w/bar_width, 0, 0, h/bar_height, 0, 0]) 
     d.add(bar_code) 
     renderPDF.draw(d, self.canv, 0, 0) 

そして、今1つのページに複数のバーコードを置くための最も簡単な方法はそうのようなTableを使用されるだろう、あなたの質問に答えるために:

だから、このようになります1 BarcodeFlowableステップ

from reportlab.platypus import SimpleDocTemplate, Table 
from reportlab.lib.pagesizes import A4 

doc = SimpleDocTemplate("test.pdf", pagesize=A4) 

table_data = [[BarCode(value='123'), BarCode(value='456')], 
       [BarCode(value='789'), BarCode(value='012')]] 

barcode_table = Table(table_data) 

parts = [] 
parts.append(barcode_table) 
doc.build(parts) 

出力:

Example of barcode table

+0

これはコード39に拡張できますか?それはウィジェットafaikを持っていません – Fourier

関連する問題