1

我目前正在使用此处描述的函数将我制作的 dxf 绘图转换为 pdf 绘图:Python convert 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')
4

1 回答 1

1

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

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

我链接的页面上有一个扩展的解决方法。我认为整个响应值得一读,而不是在这里复制粘贴。

于 2021-10-21T20:51:47.530 回答