-
Notifications
You must be signed in to change notification settings - Fork 24
fix: passa largura explícita ao inserir figura, evitando mismatch de DPI #1300
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Rossi-Luciano
merged 2 commits into
scieloorg:master
from
Rossi-Luciano:fix/figure-insert-explicit-width-pr
Aug 28, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,11 +22,12 @@ def add_figure(docx, figure_data, header_style_name='SCL Table Heading', page_at | |
|
|
||
| single_col_width = _compute_single_column_width(page_attributes) | ||
|
|
||
| target_width = content_width if layout == pdf_enum.SINGLE_COLUMN_PAGE_LABEL else single_col_width | ||
| ceiling_width = content_width if layout == pdf_enum.SINGLE_COLUMN_PAGE_LABEL else single_col_width | ||
| context = _get_docx_context(docx) | ||
| href, alt = _extract_figure_meta(figure_data) | ||
| img_path = _resolve_image_path(href, context) | ||
|
|
||
| target_width = _natural_width_capped(img_path, ceiling_width) | ||
| picture_added = _try_insert_picture(docx, img_path, target_width, page_attributes) | ||
| if not picture_added: | ||
| _add_alt_paragraph(docx, alt) | ||
|
|
@@ -214,15 +215,44 @@ def _resolve_image_path(href, context): | |
|
|
||
| return img_path | ||
|
|
||
| def _natural_width_capped(img_path, ceiling_width): | ||
| """ | ||
| Compute the image's natural width from its DPI metadata, capped at | ||
| ceiling_width - only ever shrunk to fit, never enlarged. | ||
| """ | ||
| if not (img_path and os.path.exists(img_path)): | ||
| return ceiling_width | ||
| try: | ||
| from PIL import Image | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Mover este import para o topo, removendo desta linha e de outra neste arquivo. |
||
|
|
||
| with Image.open(img_path) as im: | ||
| px_w = im.width | ||
| dpi = _infer_image_dpi(im) | ||
| natural_width = Cm((px_w / max(1.0, dpi)) * 2.54) | ||
| return natural_width if natural_width < ceiling_width else ceiling_width | ||
| except Exception: | ||
| return ceiling_width | ||
|
|
||
| def _try_insert_picture(docx, img_path, content_width, page_attributes): | ||
| """Try to insert a picture into the document, scaling it to fit content width. Returns True if successful.""" | ||
| """ | ||
| Insert a picture at content_width explicitly, then apply | ||
| _scale_picture_to_fit as a height safety net. Returns True if successful. | ||
|
|
||
| content_width is passed to add_picture(width=...) instead of left for | ||
| python-docx to infer: python-docx reads DPI metadata independently of | ||
| _infer_image_dpi (used above to compute content_width in the first | ||
| place), and the two can disagree - e.g. a PNG without DPI metadata makes | ||
| python-docx default to 72 DPI while _infer_image_dpi defaults to 96 DPI, | ||
| a ~33% size difference. Passing the width explicitly makes content_width | ||
| the actual inserted size. | ||
| """ | ||
| if not (img_path and os.path.exists(img_path)): | ||
| return False | ||
| try: | ||
| pic_para = docx.add_paragraph() | ||
| run = pic_para.add_run() | ||
| picture = run.add_picture(img_path) | ||
| picture = run.add_picture(img_path, width=content_width) | ||
|
|
||
| _scale_picture_to_fit(picture, content_width, page_attributes) | ||
| pic_para.alignment = WD_ALIGN_PARAGRAPH.CENTER | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note que:
decide_figure_layoutescolhe entre largura total e largura de coluna._natural_width_cappeddetermina a largura efetiva de inserção, limitada ao teto.Nelas há um trecho duplicado que se refere ao cálculo da largura natural:
Ainda,
decide_figure_layoutmantém o resultado comofloatem centímetros;_natural_width_cappedconverte o resultado comCm(...), produzindo um objetoLengthrepresentado internamente em EMU.As funções têm responsabilidades diferentes, mas ambas abrem a imagem e calculam sua largura natural a partir de pixels e DPI. Além da duplicação, atualmente elas produzem unidades diferentes:
decide_figure_layoutmantém umfloatem centímetros, enquanto_natural_width_cappedretornaCm/EMU.Podemos extrair uma operação única que devolva a largura natural em
Cme reutilizá-la tanto na decisão quanto no limite de inserção? Isso mantém interpretação de DPI e unidade consistentes nos dois fluxos.