如何在 react-pdf 中用一张图片填满整个页面?

9

我正在尝试在ReactJS Web应用程序中使用react-pdf将一个PDF页面制作成一个base64图像。

我已经尝试了所有我知道的方法,使图像成为A4大小的图像,并完全填充图像,以便一个图像作为一个完整的页面出现在react-pdf中。

我尝试过width:100%,height:100%,object-fill,尝试增加大小。但到目前为止,我都没有成功。

目前,图像位于中心并且未覆盖页面的所有角落。


import React, { Component } from 'react'
import ReactPDF,  { Page, Text, View, Document, StyleSheet ,  Font, Image,} from '@react-pdf/renderer';
import pic from "../pics/pic.jpeg"



// Create styles
const styles = StyleSheet.create({
    page: {
      flexDirection: 'row',
      backgroundColor: '#fff',
      width:"100%",
      orientation:"portrait"
    }, 
    image: {
        width: '100%',
        height:"100%",
        padding: 10,
        backgroundColor: 'white',
      },
  });


// Create Document Component
export default class ImageToPDF extends Component {

    render() {

        return (
     <Document >

 <Page object-fit="fill" style={styles.page} size="A4">
        <View object-fit="fill" style={styles.image}>
   <Image object-fit="fill"  style={{ padding:"0, 0, 0, 0", margin:"33%, 2rem, 2rem, 2rem",

      transform: 'rotate(90deg)'}}  src={pic} alt="images" />
   </View>
      </Page>



    </Document>
        )
    }
}

期望输出:使用react-pdf,一个图像应该出现在pdf中的一页上。

实际结果:使用react-pdf,一个图像会出现在页面中央,四周有大量空白边距。

非常感谢帮助。我真的很感激。

1个回答

4

可能有点晚了,但希望其他人也能从中受益。

我认为以下代码可以解决问题。 我做了一些修改:

  1. 视图元素有填充,我将其删除。
  2. 应用了objectFit到图像元素上,建议使用“cover”而不是“fill”。

如果这有所帮助,请告诉我。

import React, { Component } from 'react'
import ReactPDF, { Page, Text, View, Document, StyleSheet, Font, Image } from '@react-pdf/renderer';
import pic from "../pics/pic.jpeg"

// Create styles
const styles = StyleSheet.create({
    page: {
        flexDirection: 'row',
        backgroundColor: '#fff',
        width: '100%',
        orientation: 'portrait',
    },
    view: {
        width: '100%',
        height: '100%',
        padding: 0,
        backgroundColor: 'white',
    },
    image: {
        objectFit: 'cover',
    },
});


// Create Document Component
export default class ImageToPDF extends Component {

    render() {
        return (
            <Document >
                <Page object-fit="fill" style={styles.page} size="A4">
                    <View style={styles.view}>
                        <Image style={styles.image}  src={pic} alt="images" />
                    </View>
            </Page>
        </Document>
        );
  };
};

你认为它能工作还是它实际上能工作?整个问题在于React Pdf在处理图像路径时存在问题,特别是相对路径。 - Yonatan Galili
1
@YonatanGalili 我让它工作的方法是将 {pic} 更改为 base64 字符串。 - LucasBr
@user2552887,你有没有想过如何在图片上写字? - LucasBr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接