简体   繁体   English

使用pybarcode ImageWriter和docx模块将条形码图像附加到docx文件

[英]Append barcode images to docx file using pybarcode ImageWriter and docx module

How can i reduce the image size which is generated by pybarcode ImageWriter, and also how can append multiple images to docx file with proper alignment? 如何缩小pybarcode ImageWriter生成的图像大小,以及如何以正确的对齐方式将多个图像附加到docx文件?

I read about dpi option for ImageWriter but not getting how to use it. 我了解了ImageWriter的dpi选项,但未了解如何使用它。

import barcode
from barcode.writer import ImageWriter
from docx import *

if __name__ == '__main__':        
    # Default set of relationshipships - these are the minimum components of a document
    ean = barcode.get_barcode('ean', '123456789102', writer=ImageWriter())
    ean.default_writer_options['module_height'] = 3.0
    ean.default_writer_options['module_width'] = 0.1
    filename = ean.save('bar_image')    

    relationships = relationshiplist()

    # Make a new document tree - this is the main part of a Word document
    document = newdocument()

    # This xpath location is where most interesting content lives 
    docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
    # Add an image
    relationships,picpara = picture(relationships, filename,'This is a test description')
    docbody.append(picpara)

    # Create our properties, contenttypes, and other support files
    coreprops = coreproperties(title='Python docx demo',subject='A practical example of making docx from Python',creator='Mike MacCana',keywords=['python','Office Open XML','Word'])
    appprops = appproperties()
    contenttypes = contenttypes()
    websettings = websettings()
    wordrelationships = wordrelationships(relationships)

    # Save our document
        savedocx(document,coreprops,appprops,contenttypes,websettings,wordrelationships,'sample_barcode.docx')

Generally, the barcode.writer doesn't give a parameter on the generated output image size, and you may ask PIL help. 通常,barcode.writer在生成的输出图像大小上提供参数,您可能会要求PIL帮助。 And the proper alignment is quite not accurate to code, but you may try using tables to make them in right place. 而且正确的对齐方式对于代码来说是相当不准确的,但是您可以尝试使用表将它们放置在正确的位置。

In PIL, you can resize the png image to (480,320) by 在PIL中,您可以通过以下方式将png图像的大小调整为(480,320):

from PIL import Image
im = Image.open("barcode.png")
im.resize((480,320)).save("barcode_resized.png")

And for the docx file, some table example is here , you may need know what proper aliment is and then type the code. 对于docx文件, 这里有一些表示例,您可能需要知道什么是适当的饮食,然后键入代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM