用JavaScript via C++保护PDF文档
Contents
[
Hide
]
有时,开发人员需要处理加密的PDF文件。例如:
- 通过所有者密码和用户密码保护文档,以防止任何人都能打开它。
- 在打开文档之后,设置文档的限制或权限。例如,限制文档内容是否可以打印或提取。
本文解释了在将电子表格保存为PDF时如何传递PDF安全选项。
Aspose.Cells 提供 PdfSecurityOptions 支持安全性功能。保存为 PDF 时,可以设置所有者密码和用户密码。加密的 PDF 文件需要这些密码才能打开查看。
- 用户密码可以为空或空字符串;在这种情况下,打开 PDF 文档时不需要用户密码。 使用正确的所有者密码打开 PDF,允许完全访问(没有任何访问限制)。
- 使用正确的用户密码打开PDF文档(或打开没有用户密码的文档)允许进行有限访问,如权限所述。
下面的示例代码描述了如何使用Aspose.Cells保护PDF文件。
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Secure PDF Example</title>
</head>
<body>
<h1>Secure PDF Example</h1>
<input type="file" id="fileInput" accept=".xls,.xlsx" />
<button id="runExample">Run Example</button>
<a id="downloadLink" style="display: none;">Download Result</a>
<div id="result"></div>
</body>
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat, PdfSaveOptions, PdfSecurityOptions, Utils } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
const fileInput = document.getElementById('fileInput');
if (!fileInput.files.length) {
document.getElementById('result').innerHTML = '<p style="color: red;">Please select an Excel file.</p>';
return;
}
const file = fileInput.files[0];
const arrayBuffer = await file.arrayBuffer();
// Instantiating a Workbook object from the uploaded file
const workbook = new Workbook(new Uint8Array(arrayBuffer));
// Create PDF save options and security options
const saveOption = new PdfSaveOptions();
saveOption.securityOptions = new PdfSecurityOptions();
// Set security options (converted from getters/setters to properties)
saveOption.securityOptions.userPassword = "user";
saveOption.securityOptions.ownerPassword = "owner";
saveOption.securityOptions.extractContentPermission = false;
saveOption.securityOptions.printPermission = false;
// Save the workbook to PDF with security options
const outputData = workbook.save(SaveFormat.Pdf, saveOption);
const blob = new Blob([outputData], { type: "application/pdf" });
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'securepdf_test.out.pdf';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Secure PDF';
document.getElementById('result').innerHTML = '<p style="color: green;">PDF generated successfully! Click the download link to get the secured PDF file.</p>';
});
</script>
</html>
如果电子表格包含公式,最好在将其呈现为PDF之前调用Workbook.calculateFormula()。这样可以确保重新计算依赖公式的值,并且在PDF中呈现正确的值。