You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R生成含二维码的PDF:4×6布局间距调整求助

问题描述

我正在用R生成包含二维码图片的PDF,需要将图片排列成4×6的布局。目前已编写图片加载代码(后续要改成循环处理2000余张图片),但生成的PDF存在上下及右侧边距过大的问题。尝试在循环中设置par(mar = c(4,0,0,0))未生效,也没找到padding参数,请问该如何调整间距?

现有代码如下:

# 导入库
library(qrcode)
library(imager)

# 清空工作区
rm(list = ls())

filenames <- list.files(path = "./QR/2/")

im <- load.image(paste0("./QR/2/",filenames[1]))

im <- list()
for(i in 1:24){
  im[[i]] <- load.image(paste0("./QR/2/",filenames[i]))
}

pdf("./QR/2/stickervellen/1.pdf", paper = "a4")
par(mfrow = c(6,4), mar=c(0,0,0,0))
for(i in 1:24){
  par(mar = c(4,0,0,0))
  plot(im[[i]], axes = F)
}
dev.off()
解决方案

以下几种方法可有效调整PDF中的图片间距与边距:

方法1:优化pdf()与par()参数设置

  • 在pdf()中指定A4纸精确尺寸(转成R默认的英寸单位),同时关闭冗余设置:
    pdf("./QR/2/stickervellen/1.pdf", width = 21/2.54, height = 29.7/2.54, paper = "a4", useDingbats = FALSE)
    
  • 统一设置par()的边距参数,避免循环内重复设置:
    par(mfrow = c(6,4), mar = c(0,0,0,0), mai = c(0,0,0,0), omi = c(0,0,0,0), xpd = NA)
    
  • 循环内仅保留绘图命令,移除多余的par()调用:
    for(i in 1:24){
      plot(im[[i]], axes = F, xlab = "", ylab = "")
    }
    

方法2:用grid包实现精准排版

将imager图片转为grid对象,直接控制每个图片的位置与尺寸:

library(grid)

pdf("./QR/2/stickervellen/1.pdf", width = 21/2.54, height = 29.7/2.54, paper = "a4")
grid.newpage()
# 按6行4列无间隙填充页面
for(row in 1:6){
  for(col in 1:4){
    idx <- (row-1)*4 + col
    img <- rasterGrob(im[[idx]], interpolate = FALSE)
    # 计算单元格位置,确保无间距
    pushViewport(viewport(x = (col-0.5)/4, y = (6 - row + 0.5)/6, width = 1/4, height = 1/6))
    grid.draw(img)
    popViewport()
  }
}
dev.off()

方法3:统一调整图片尺寸匹配布局

若二维码图片比例不符,可在加载时统一调整为单元格尺寸,最大化利用页面空间:

im <- list()
# A4纸尺寸(单位mm)
target_width <- 210
target_height <- 297
# 计算单个单元格尺寸
cell_width <- target_width / 4
cell_height <- target_height / 6

for(i in 1:24){
  img <- load.image(paste0("./QR/2/",filenames[i]))
  img <- resize(img, size_x = cell_width, size_y = cell_height)
  im[[i]] <- img
}

搭配方法1的参数设置即可消除冗余边距。

内容的提问来源于stack exchange,提问作者JadaLovelace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:10:32