简体   繁体   English

Expo - 减少 iOS 设备上的 PDF 文件大小

[英]Expo - reduce PDF filesize on iOS devices

I'm currently creating an A4 PDF within my Expo-App, using the "expo-print" API ( printtofileasync ).我目前正在我的 Expo-App 中创建一个 A4 PDF,使用“expo-print” API ( printtofileasync )。 The PDF includes images (photos taken from the device) and some text. PDF 包含图像(从设备拍摄的照片)和一些文本。 I've set the PDF size to 595 width, 842 height (A4 dimensions).我已将 PDF 尺寸设置为 595 宽,842 高(A4 尺寸)。 Unfortunately the size of the PDF is too large for my requirements (1,9MB with only 1 image).不幸的是,PDF 的大小对于我的要求来说太大了(1.9MB,只有 1 个图像)。

I was able to reduce the PDF size on Android by decreasing the image size, but that does not work on iOS.我能够通过减小图像大小来减小 Android 上的 PDF 大小,但这在 iOS 上不起作用。 I have the suspicion that on iOS Expo is simply "making screenshots" of the page, therefore changing the image size has no effect.我怀疑在 iOS Expo 上只是“制作屏幕截图”的页面,因此更改图像大小没有效果。 I've already tried to decrease the whole PDF size to A5, but that's not a solution, because the PDFs needs to be printed afterwards on A4.我已经尝试将整个 PDF 大小减小到 A5,但这不是一个解决方案,因为 PDF 之后需要在 A4 上打印。

Any help would be appreciated!任何帮助,将不胜感激!

Update: currently this my code:更新:目前这是我的代码:

const { uri, base64 } = await Print.printToFileAsync({
    width: 595,
    height: 842,
    html: 'data...',
    base64: true,
});

Share.share({
    url: 'data:application/pdf;base64,' + base64,
});

I have the same problem, I change my pdf creator because html creates variable size pdf and it depends on the resolution device, I use pdf-lib it works in javascript, you can create or modify pdf, I write small example in Expo, I plan to create a library to do Additional, you can fill PDF NOTE: it similar to react-native-pdf-lib but working in only enviroment javascript I have the same problem, I change my pdf creator because html creates variable size pdf and it depends on the resolution device, I use pdf-lib it works in javascript, you can create or modify pdf, I write small example in Expo, I计划创建一个库来做附加,你可以填写 PDF注意:它类似于react-native-pdf-lib但仅在环境 javascript 中工作

My App.tsx example:我的 App.tsx 示例:

import React from "react";
import { StyleSheet, View, Text, Button } from "react-native";
import { Asset } from "expo-asset";
import * as Print from "expo-print";
import { degrees, PDFDocument, rgb, StandardFonts } from "pdf-lib";

export default function App({ context }: any) {
  return (
    <View style={styles.container}>
      <Button
        title="Generate PDF"
        onPress={async () => {
          const req = new XMLHttpRequest();
          /* const templateUri = Asset.fromModule(
            require("./assets/template.pdf")
          );
          console.log(templateUri); */
          const url =  'https://pdf-lib.js.org/assets/with_update_sections.pdf' // templateUri.uri
          req.open("GET", url, true);
          req.responseType = "blob";
          /*   req.onprogress = e => (t.progress = e.loaded); */
          req.onload = () => {
            const blob = req.response;
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onloadend = async function() {
              const base64data = reader.result as string; // template pdf in base64
              const pdfDoc = await PDFDocument.load(base64data);
              const helveticaFont = await pdfDoc.embedFont(
                StandardFonts.Helvetica
              );

              const pages = pdfDoc.getPages();
              const firstPage = pages[0];
              const { width, height } = firstPage.getSize();
              console.log(width, height);
              firstPage.drawText('This text was added with JavaScript!', {
                x: 5,
                y: height / 2 + 300,
                size: 50,
                font: helveticaFont,
                color: rgb(0.95, 0.1, 0.1),
                rotate: degrees(-45),
              });

              const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
              Print.printAsync({ uri: pdfDataUri });
            };
          };
          req.onerror = console.error;
          req.send();
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

You can try using the base64 string and decoding it back to the pdf file.您可以尝试使用base64字符串并将其解码回 pdf 文件。 i think it should be of smaller size, Follow along.我认为它应该是更小的尺寸,跟随。

  1. Use Expo Print API to get the pdf file in question, remember to set the base64 to true.使用 Expo 打印 API 得到有问题的 pdf 文件,记得将 Z95A1446A7120E4AFD5Z0C0E768 设置为 true。
import * as Print from 'expo-print';

const pdf = Print.printToFileAsync({
    width: 612,    // <=== your width
    height: 612,   // <=== your height
    base64: true
});
  1. You can use this or this library to decode back the base64 file.您可以使用这个这个库来解码 base64 文件。
import * as Print from 'expo-print';
import base64 from 'base64'; // or import base64 from 'react-native-base64'

const pdf = Print.printToFileAsync({
     width: 612,    // <=== your width
     height: 612,   // <=== your height
     base64: true
});

const pdfDecoded = base64(pdf);

The pdfDecoded will hold your new pdf file and it should be of smaller size, you can either send it to your server or display it. pdfDecoded将保存您的新 pdf 文件,它应该较小,您可以将其发送到您的服务器或显示它。

I have not tested this just my 2 cents.我还没有测试过这只是我的 2 美分。

Hope this Helps!希望这可以帮助!

If you have a requirement to take digital photos and add them to a PDF document and have a constraint on how big the PDF file size can be, before you start trying to make the page size smaller in order to shrink the size of the document....I'd strongly suggest you consider optimizing the created PDFs.如果您需要拍摄数码照片并将它们添加到 PDF 文档中,并且对 PDF 文件的大小有限制,则在开始尝试缩小页面大小以缩小文档大小之前。 ...我强烈建议您考虑优化创建的 PDF。

Not all PDF software is created equal and many creators birth documents that are bloated and can benefit greatly from being optimized.并非所有的 PDF 软件都是平等的,许多创作者出生的文档都是臃肿的,并且可以从优化中受益匪浅。

Just a note that 1.9MB is a bit arbitrary especially when dealing with digital image(s), you may need to reconsider that requirement with your stakeholders depending on the quality and number of input images as well.请注意,1.9MB 有点随意,尤其是在处理数字图像时,您可能需要根据输入图像的质量和数量与利益相关者重新考虑该要求。

My company offers a tool called PDF Optimizer which can help.我公司提供了一个名为 PDF Optimizer的工具,它可以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM