为什么从缓冲区创建的Uint8Array()返回为空?

huangapple go评论74阅读模式
英文:

why does a Uint8Array() from buffer returns empty?

问题

我正在尝试加载一个字体供pdf-lib使用。为了使用它,我必须为pdfDoc.embedFont(font);提供一个Uint8Array。

出于某种原因,无论我何时创建Uint8Array,它都返回空的结果。ArrayBuffer 返回了一些内容,所以我感到相当困惑。我对JS还很陌生,如果这是一个愚蠢的问题,我深感抱歉。

var request = new XMLHttpRequest();

request.open("GET", "./resources/skill_positioning.json", false);
request.send(null)
const positionData = JSON.parse(request.responseText);

async function createPdf() {
    var fontkit = window.fontkit;
    var pdflib = window.PDFLib;
    const url = './resources/character_sheet_blank.pdf';
    const existingPdfBytes = await fetch(url).then((res) =>
        res.arrayBuffer(),
    );

    const pdfDoc = await pdflib.PDFDocument.load(existingPdfBytes)

    pdfDoc.registerFontkit(fontkit);

    const customFont = fetch('./resources/fonts/arialnb.ttf').then((response) => {
        const buffer = response.arrayBuffer();
        return new Uint8Array(buffer);
    }).then((buffer) => {
        return fontkit.create(buffer);
    }).then((font) => {
        return pdfDoc.embedFont(font);
    }).then((customFont) => {
        const pages = pdfDoc.getPages()
        const firstPage = pages[0]
        const { width, height } = firstPage.getSize()

        var curRow = 1;
        var curCollumn = 0;
        firstPage.drawText('This text was added with JavaScript!', {
            x: positionData.boxes[0].x,
            y: height - (positionData.boxes[0].y + curRow * positionData.row_height),
            size: 110,
            font: customFont,
            color: pdflib.rgb(0.0, 0.0, 0.0),
        })
        return pdfDoc;
    }).then((pdfDoc) => {
        const pdfBytes = pdfDoc.save();
        download(pdfBytes, "character_sheet.pdf");
    })
}

我已经尝试在.then()之前和之后从数组缓冲区创建一个新的Uint8Array。

英文:

I am trying to load a font for pdf-lib to use. In order to use it, i must provide a Uint8Array for pdfDoc.embedFont(font);
For some reason, whenever i create the UInt8Array, it returns empty. The ArrayBuffer is returning something so i am quite confused. I am new to JS so my apologies if this is a dumb question.

var request = new XMLHttpRequest();
request.open("GET", "./resources/skill_positioning.json", false);
request.send(null)
const positionData = JSON.parse(request.responseText);
async function createPdf() {
var fontkit = window.fontkit;
var pdflib = window.PDFLib;
const url = './resources/character_sheet_blank.pdf';
const existingPdfBytes = await fetch(url).then((res) =>
res.arrayBuffer(),
);
const pdfDoc = await pdflib.PDFDocument.load(existingPdfBytes)
pdfDoc.registerFontkit(fontkit);
const customFont = fetch('./resources/fonts/arialnb.ttf').then((response) => {
const buffer = response.arrayBuffer();
return new Uint8Array(buffer);
}).then((buffer) => {
return fontkit.create(buffer);
}).then((font) => {
return pdfDoc.embedFont(font);
}).then((customFont) => {
const pages = pdfDoc.getPages()
const firstPage = pages[0]
const { width, height } = firstPage.getSize()
var curRow = 1;
var curCollumn = 0;
firstPage.drawText('This text was added with JavaScript!', {
x: positionData.boxes[0].x,
y: height - (positionData.boxes[0].y + curRow * positionData.row_height),
size: 110,
font: customFont,
color: pdflib.rgb(0.0, 0.0, 0.0),
})
return pdfDoc;
}).then((pdfDoc) => {
const pdfBytes = pdfDoc.save();
download(pdfBytes, "character_sheet.pdf");
})
}

I have tried to create a new Uint8Array from the array buffer, before and after .then()

答案1

得分: 0

arrayBuffer() 返回一个Promise。因此,你应该这样写:

fetch('./resources/fonts/arialnb.ttf').then((response) => {
    return response.arrayBuffer();
}).then((buffer) => {
    return fontkit.create(buffer);
})

将你的fetch调用结果分配给const customFont 是没有意义的,因为你链中的最后一个then块不返回任何内容。

另外,考虑使用async/await语法,它可以使Promise代码更加直观。实际上,在函数的前半部分已经在使用async/await了。为什么要回到then链呢?

const response = await fetch('./resources/fonts/arialnb.ttf');
const buffer = await response.arrayBuffer();
const font = await fontkit.create(buffer);
const customFont = await pdfDoc.embedFont(font);
//... 继续使用customFont
英文:

arrayBuffer() returns a Promise. Therefore you should write

fetch('./resources/fonts/arialnb.ttf').then((response) => {
    return response.arrayBuffer();
}).then((buffer) => {
    return fontkit.create(buffer);
})

Assigning the result of your fetch call to const customFont is meaningless because your last then block in the chain returns nothing.

Also consider using the async/await syntax which makes promise code more intuitive. In fact you are already using async/await in the first half of the function. Why switch back to then chain?

const response = await fetch('./resources/fonts/arialnb.ttf');
const buffer = await response.arrayBuffer();
const font = await fontkit.create(buffer);
const customFont = await pdfDoc.embedFont(font);
//... continue to work with customFont

huangapple
  • 本文由 发表于 2023年6月19日 08:25:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502988.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定