代码之家  ›  专栏  ›  技术社区  ›  Paul Luczak

如何使用pdfMake动态居中列中的元素?

  •  0
  • Paul Luczak  · 技术社区  · 5 月前

    我正在使用pdfMake生成PDF,但在页面上的列中动态居中元素时遇到了问题。具体来说,我想在一列中居中放置图像和一些文本,但文本内容可能会发生变化,可能会换行,因此我需要相应地调整居中位置。

    下面是我目前使用的代码:

    const fs = require('fs');
    const pdfMake = require('pdfmake/build/pdfmake');
    const vfsFonts = require('pdfmake/build/vfs_fonts');
    const sharp = require('sharp');
    
    const inputImagePath = './photos/profil.png';
    const outputImagePath = './photos/profil_circle.png';
    
    sharp(inputImagePath)
      .metadata()
      .then(({ width, height }) => {
        const diameter = Math.min(width, height);
    
        return sharp(inputImagePath)
          .resize(diameter, diameter)
          .composite([{
            input: Buffer.from(
              `<svg><circle cx="${diameter / 2}" cy="${diameter / 2}" r="${diameter / 2}" fill="white"/></svg>`
            ),
            blend: 'dest-in'
          }])
          .png()
          .toFile(outputImagePath);
      })
      .then(() => {
        const photoBase64 = fs.readFileSync(outputImagePath, { encoding: 'base64' });
    
        const publicSansLight = fs.readFileSync('./fonts/PublicSans/PublicSans-Light.ttf', { encoding: 'base64' });
        const publicSansLightItalic = fs.readFileSync('./fonts/PublicSans/PublicSans-LightItalic.ttf', { encoding: 'base64' });
        const publicSansBold = fs.readFileSync('./fonts/PublicSans/PublicSans-Bold.ttf', { encoding: 'base64' });
    
        pdfMake.vfs = {
          ...vfsFonts.pdfMake.vfs,
          'PublicSans-Light.ttf': publicSansLight,
          'PublicSans-LightItalic.ttf': publicSansLightItalic,
          'PublicSans-Bold.ttf': publicSansBold,
          'profil_circle.png': photoBase64
        };
    
        const fonts = {
          PublicSans: {
            normal: 'PublicSans-Light.ttf',
            bold: 'PublicSans-Bold.ttf',
            italics: 'PublicSans-LightItalic.ttf',
            bolditalics: 'PublicSans-Bold.ttf'
          }
        };
    
        const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
    
        const docDefinition = {
          pageSize: 'A4',
          pageMargins: [20, 20, 20, 20],
          defaultStyle: {
            font: 'PublicSans'
          },
          content: [
            {
              columns: [
                {
                  width: 'auto',
                  image: 'profil_circle.png',
                  fit: [125, 125],
                  alignment: 'center'
                },
                {
                  width: 400,
                  stack: [
                    {
                      text: `${data.firstname} ${data.lastname}`,
                      style: 'headerTitle'
                    },
                    {
                      text: `${data.city}, ${data.country}`,
                      style: 'header',
                      wordBreak: 'break-all'
                    },
                    {
                      text: data.tel,
                      style: 'header',
                      wordBreak: 'break-all'
                    },
                    {
                      text: data.email,
                      style: 'header',
                      wordBreak: 'break-all'
                    }
                  ]
                }
              ],
              columnGap: 25,
            }
          ],
          styles: {
            headerTitle: {
              fontSize: 20,
              bold: true,
              color: '#37352F'
            },
            header: {
              fontSize: 14,
              color: '#747370'
            }
          }
        };
    
        pdfMake.createPdf(docDefinition, undefined, fonts).getBuffer(buffer => {
          fs.writeFileSync('CV.pdf', buffer);
          fs.unlinkSync(outputImagePath);
          console.log('CV created and circular image deleted.');
        });
      })
      .catch(err => {
        console.error('Error:', err);
      });
    

    我面临的问题是,左列(圆形图像)和右列(文本堆栈)中的元素没有像预期的那样垂直居中。我尝试过在columns对象中使用对齐:“center”,但似乎不起作用。此外,由于文本内容可以更改并换行为多行,我需要动态调整中心。

    我错过了什么?即使文本可能导致换行,我如何才能将这些元素正确地居中放置在各自的列中?任何帮助都将不胜感激!

    提前感谢!

    0 回复  |  直到 5 月前