页面格式

pageFormat 选项控制文档中每页的尺寸和边距。这有助于您的内容看起来一致且专业,尤其是在打印或导出时。

内置格式

Pages 使用标准 CSS 像素——1 英寸等于 96 像素——因此下面的尺寸与浏览器实际渲染的结果一致。Pages 扩展会在内部保留小数像素值,以避免布局随累积产生偏移;此处显示的整数为便于阅读而四舍五入后的结果。

名称尺寸(cm)尺寸(px)边距(cm:上、右、下、左)边距(px)
A421.0 × 29.7794 × 11232.5, 2.0, 2.5, 2.095, 76, 95, 76
A329.7 × 42.01123 × 15872.5, 2.0, 2.5, 2.095, 76, 95, 76
A514.8 × 21.0559 × 7942.0, 1.5, 2.0, 1.576, 57, 76, 57
Letter21.59 × 27.94816 × 10562.54, 2.54, 2.54, 2.5496, 96, 96, 96
Legal21.59 × 35.56816 × 13452.54, 2.54, 2.54, 2.5496, 96, 96, 96
Tabloid27.94 × 43.181056 × 16332.54, 2.54, 2.54, 2.5496, 96, 96, 96

每种内置格式都自带默认边距和尺寸。若要自定义它们,请定义你自己的格式对象——见下方的自定义页面格式

使用内置格式

Pages.configure({
  pageFormat: 'Letter',
})

使用内置格式的常量

你也可以导入内置页面格式常量,以获得更好的自动补全和类型安全:

import { PAGE_FORMATS } from '@tiptap-pro/extension-pages'

Pages.configure({
  pageFormat: PAGE_FORMATS.Letter,
})

这与使用字符串字面量等效:

Pages.configure({
  pageFormat: 'Letter',
})

你可以选择自己喜欢的方式。

自定义页面格式

你可以通过提供一个包含所需尺寸和边距的页面格式对象来定义自定义页面格式:

Pages.configure({
  pageFormat: {
    id: 'custom-page-format',
    width: cmToPixels(22.94),
    height: cmToPixels(35.18),
    margins: {
      top: cmToPixels(2.54),
      right: cmToPixels(2.54),
      bottom: cmToPixels(2.54),
      left: cmToPixels(2.54),
    },
  },
})

提示

在此示例中,我们使用了cmToPixels工具函数,以厘米为单位定义页面尺寸和边距,使其更便于使用熟悉的打印度量单位。 你可以在实用工具参考中了解更多关于 cmToPixels 的内容。

页面边距

通过使用自定义页面格式,可以自定义页面边距。内置格式具有固定边距,但你可以创建带有自定义边距的格式:

Pages.configure({
  pageFormat: {
    id: 'custom-layout',
    width: 794, // px
    height: 1123, // px
    margins: {
      top: 60, // px
      right: 40, // px
      bottom: 60, // px
      left: 40, // px
    },
  },
})

编程方式更改页面格式

在编辑器初始化后,使用 setPageFormat 命令更改页面格式:

// 切换到内置格式
editor.commands.setPageFormat('A4')

// 切换到自定义格式
editor.commands.setPageFormat({
  id: 'custom-wide-page-format',
  width: cmToPixels(27.94),
  height: cmToPixels(43.18),
  margins: {
    top: cmToPixels(2.54),
    right: cmToPixels(2.54),
    bottom: cmToPixels(2.54),
    left: cmToPixels(2.54),
  },
})

监听页面格式变化

使用 onPageFormatChange 回调函数来响应页面格式的变化:

Pages.configure({
  pageFormat: 'A4',
  onPageFormatChange: (pageFormat) => {
    console.log('页面格式已更改为:', pageFormat)
    // 更新界面,保存偏好设置等
  },
})

灵活性

通过自定义页面格式,你可以完全控制页面尺寸和边距,创建所需的精准布局。