HarmonyOS PDF添加水印后展示白屏?

pdf添加水印的时机在哪里,添加水印放在

let result = pdfDocument.loadDocument(this.filePath);

代码之后,pdf展示白屏,添加水印的代码如下:

addTextWatermark(pdfDocument: pdfService.PdfDocument, path: string) {
  let wminfo: pdfService.TextWatermarkInfo = new pdfService.TextWatermarkInfo();
  wminfo.watermarkType = pdfService.WatermarkType.WATERMARK_TEXT;
  wminfo.content = "This is watermark";
  wminfo.textSize = 30;
  wminfo.textColor = 200;
  wminfo.fontInfo = new pdfService.FontInfo();
  wminfo.fontInfo.fontPath = font.getFontByName("HarmonyOS Sans").path;
  wminfo.opacity = 0.5;
  wminfo.isOnTop = true;
  wminfo.rotation = 45;
  wminfo.scale = 1.5;
  wminfo.opacity = 0.5;
  wminfo.verticalAlignment = pdfService.WatermarkAlignment.WATERMARK_ALIGNMENT_TOP;
  wminfo.horizontalAlignment = pdfService.WatermarkAlignment.WATERMARK_ALIGNMENT_LEFT;
  wminfo.horizontalSpace = 1.0;
  wminfo.verticalSpace = 1.0;
  pdfDocument.addWatermark(wminfo, 1, 18, true, true);
  pdfDocument.saveDocument(path);
}
阅读 490
1 个回答

1、请确认选用的字体是否存在,在获取字体后,可以打印下字体信息,如不存在请更换字体后重试;

2、字体可以在system/fonts/目录下查看,可能需要多试几个,在传入字体名称时,需要将下划线换成空格;

片段示例:

// let fontInfo: font.FontInfo = font.getFontByName("HarmonyOS Sans");
//需要去掉下划线: /system/fonts/HarmonyOS_Sans_Digit.ttf
let fontInfo: font.FontInfo = font.getFontByName("HarmonyOS Sans Digit");
console.error(TAG, 'addTextWatermark fontInfo:' + JSON.stringify(fontInfo));
wminfo.fontInfo.fontPath = fontInfo.path;

完整示例:

async addTextWatermark(pdfDocument: pdfService.PdfDocument, path: string) {
  console.log(TAG, "addTextWatermark, path: " + path);
  if (await fs.access(path)) {
    fs.unlinkSync(path);
  }
  try {
    let wminfo: pdfService.TextWatermarkInfo = new pdfService.TextWatermarkInfo();
    wminfo.watermarkType = pdfService.WatermarkType.WATERMARK_TEXT;
    wminfo.content = "This is watermark";
    wminfo.textSize = 30;
    // wminfo.textColor = 0x000000;
    wminfo.textColor = 200;
    wminfo.fontInfo = new pdfService.FontInfo();
    // let fontInfo: font.FontInfo = font.getFontByName("HarmonyOS Sans");
    // /system/fonts/HarmonyOS_Sans_Digit.ttf
    let fontInfo: font.FontInfo = font.getFontByName("HarmonyOS Sans Digit");
    console.error(TAG, 'addTextWatermark fontInfo:' + JSON.stringify(fontInfo));
    wminfo.fontInfo.fontPath = fontInfo.path;
    wminfo.opacity = 0.5;
    wminfo.isOnTop = false;
    wminfo.rotation = 45;
    wminfo.scale = 1.5;
    wminfo.opacity = 0.5;
    wminfo.verticalAlignment = pdfService.WatermarkAlignment.WATERMARK_ALIGNMENT_TOP;
    wminfo.horizontalAlignment = pdfService.WatermarkAlignment.WATERMARK_ALIGNMENT_LEFT;
    wminfo.horizontalSpace = 1.0;
    wminfo.verticalSpace = 1.0;
    pdfDocument.addWatermark(wminfo, 0, pdfDocument.getPageCount(), true, true);
    pdfDocument.saveDocument(path);
  } catch (e) {
    console.error(TAG, 'addTextWatermark errMsg:' + JSON.stringify(e));
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏