我使用了 Microsoft
提供的以下 JS 代码来将文档保存为 PDF
:
Office.context.document.getFileAsync(Office.FileType.Pdf,
function(result) {
if (result.status == "succeeded") {
var myFile = result.value;
var sliceCount = myFile.sliceCount;
var slicesReceived = 0, gotAllSlices = true, docdataSlices = [];
console.log("File size:" + myFile.size + " #Slices: " + sliceCount);
// Now, you can call getSliceAsync to download the files,
// as described in the previous code segment (compressed format).
// Get the file slices.
getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
myFile.closeAsync();
}
else {
console.log("Error:", result.error.message);
}
}
);
function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived) {
file.getSliceAsync(nextSlice, function (sliceResult) {
if (sliceResult.status == "succeeded") {
if (!gotAllSlices) { // Failed to get all slices, no need to continue.
return;
}
// Got one slice, store it in a temporary array.
// (Or you can do something else, such as
// send it to a third-party server.)
docdataSlices[sliceResult.value.index] = sliceResult.value.data;
if (++slicesReceived == sliceCount) {
// All slices have been received.
file.closeAsync();
onGotAllSlices(docdataSlices);
}
else {
getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived);
}
}
else {
gotAllSlices = false;
file.closeAsync();
console.log("getSliceAsync Error:", sliceResult.error.message);
}
});
}
function onGotAllSlices(docdataSlices) {
var docdata = [];
for (var i = 0; i < docdataSlices.length; i++) {
docdata = docdata.concat(docdataSlices[i]);
}
var fileContent = new String();
for (var j = 0; j < docdata.length; j++) {
fileContent += String.fromCharCode(docdata[j]);
}
console.log('Final PDF content is received and stored in fileContent.');
send_file_content(fileContent);
}
function send_file_content(word_doc) {
var formData = new FormData();
var blob = new Blob([word_doc], { type: "application/pdf"});
formData.append("file", blob);
$.ajax({
type: 'POST',
url: 'My-upload-URL',
data: formData,
processData: false,
contentType: false
}).done(function(data) {
console.log('* Word Document successfully uploaded: ', data.filepath);
});
}
我很确定服务器端没问题,因为我已经上传了无数的 PDF 文档并且它按预期工作,但是当我通过上面的 JS
代码上传 Word PDF 文档时,我得到了一个服务器端的空白页。如果 word 文档包含 3 页,那么我将在服务器端获得 3 个空白页作为 PDF 文件。
最佳答案
Microsoft 文档
带有charCodeAt
函数,它会破坏数据并生成一个空白的 PDF 文档。
我没有使用那个函数,而是直接在字节数组上使用了 Uint8Array
:
var blob = new Blob([new Uint8Array(myFinalByteArray)], { type: 'application/pdf' });
然后使用 FormData
将 Blob
上传到远程服务器。这种方法解决了这个问题。
关于javascript - 为什么使用 API 上传 Word OfficeJS PDF 文档会保存一个空的 PDF 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54265976/