【问题标题】:Matplotlib scaling an image when saving a converted dxf as PDF将转换后的 dxf 保存为 PDF 时,Matplotlib 缩放图像
【发布时间】:2021-10-08 10:36:02
【问题描述】:

我目前正在使用此处描述的函数将我制作的 dxf 绘图转换为 pdf 绘图:Python converting DXF files to PDF or PNG or JPEG。 (我也在下面放代码)

问题是,当我转换为 pdf 时,代码会自动缩放绘图以使其适合特定大小。现在我需要关闭它,或者有办法知道它使用的比例因子是什么。

完整代码如下:

import matplotlib.pyplot as plt
import ezdxf
from ezdxf.addons.drawing import RenderContext, Frontend
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
# import wx
import glob
import re


class DXF2IMG(object):

    default_img_format = '.png'
    default_img_res = 300
    def convert_dxf2img(self, names, img_format=default_img_format, img_res=default_img_res):
        for name in names:
            doc = ezdxf.readfile(name)
            msp = doc.modelspace()
            # Recommended: audit & repair DXF document before rendering
            auditor = doc.audit()
            # The auditor.errors attribute stores severe errors,
            # which *may* raise exceptions when rendering.
            if len(auditor.errors) != 0:
                raise exception("The DXF document is damaged and can't be converted!")
            else :
                fig = plt.figure()
                ax = fig.add_axes([0, 0, 1, 1])
                ctx = RenderContext(doc)
                ctx.set_current_layout(msp)
                ctx.current_layout.set_colors(bg='#FFFFFF')
                out = MatplotlibBackend(ax)
                Frontend(ctx, out).draw_layout(msp, finalize=True)

                img_name = re.findall("(\S+)\.",name)  # select the image name that is the same as the dxf file name
                first_param = ''.join(img_name) + img_format  #concatenate list and string
                fig.savefig(first_param, dpi=img_res)


if __name__ == '__main__':
    first =  DXF2IMG()
    first.convert_dxf2img(['test.DXF'],img_format='.pdf')

【问题讨论】:

    标签: python matplotlib pdf dxf ezdxf


    【解决方案1】:

    来自 github 讨论帖:https://github.com/mozman/ezdxf/discussions/357

    这可以通过在保存前仔细设置图形大小以不特定于 ezdxf 的方式解决。 Matplotlib 在测量方面相当复杂。我有一个似乎运行良好的解决方案,但由于计算是使用浮点数完成的,但最终像素是离散测量,因此可能至少有 1 个像素。可能还有很多其他的东西,比如线宽会产生影响。 ...您可以通过指定所需的 units_to_pixels 转换因子并缩放图形大小来计算所需的图形大小,以便数据跨越正确的像素数。这假设图形纵横比已经正确,因为我的解决方案对宽度和高度使用了相同的比例因子。

    在我链接的页面上有一个扩展的解决方法。与其在此处复制粘贴,我认为整个响应值得一读。

    【讨论】:

      猜你喜欢
      • 2019-08-13
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      相关资源
      最近更新 更多