Java Créer un formulaire à remplir dans Word
Table des matières
Installer avec Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
Liens connexes
Word vous permet de créer des formulaires que d'autres personnes peuvent utiliser pour saisir des informations. Les formulaires à remplir sont utilisés à diverses fins. Les ressources humaines utilisent des formulaires pour collecter des informations sur les employés et les consultants. Les services marketing utilisent des formulaires pour enquêter sur la satisfaction des clients à l'égard de leurs produits et services. Les organisations utilisent des formulaires pour inscrire des membres, des étudiants ou des clients. Certains des outils que vous utiliserez lors de la création d'un formulaire incluent :
- Contrôles de contenu:zones dans lesquelles les utilisateurs saisissent des informations dans un formulaire.
- Tableaux: les tableaux sont utilisés dans les formulaires pour aligner le texte et les champs de formulaire, ainsi que pour créer des bordures et des cadres.
- Protection: permet aux utilisateurs de remplir les champs mais pas d'apporter des modifications au reste du document.
Les contrôles de contenu dans Word sont des conteneurs de contenu qui permettent aux utilisateurs de créer des documents structurés. Un document structuré contrôle l'endroit où le contenu apparaît dans le document. Il existe essentiellement dix types de contrôles de contenu disponibles dans Word 2013. Cet article explique comment créer un formulaire à remplir dans Word composé des sept contrôles de contenu courants suivants utilisant Spire.Doc for Java.
Contrôle du contenu | Description |
Texte brut | Un champ de texte limité au texte brut, donc aucun formatage ne peut être inclus. |
Texte riche | Champ de texte pouvant contenir du texte formaté ou d'autres éléments, tels que des tableaux, des images ou d'autres contrôles de contenu. |
Image | Accepte une seule image. |
La liste déroulante | Une liste déroulante affiche une liste prédéfinie d'éléments parmi lesquels l'utilisateur peut choisir. |
Boîte combo | Une zone de liste déroulante permet aux utilisateurs de sélectionner une valeur prédéfinie dans une liste ou de saisir leur propre valeur dans la zone de texte du contrôle. |
Case à cocher | Une case à cocher fournit un widget graphique qui permet à l'utilisateur de faire un choix binaire : oui (coché) ou non (non coché). |
Sélecteur de date | Contient un contrôle de calendrier à partir duquel l'utilisateur peut sélectionner une date. |
Installer Spire.Doc for Java
Tout d'abord, vous devez ajouter le fichier Spire.Doc.jar en tant que dépendance dans votre programme Java. Le fichier JAR peut être téléchargé à partir de ce lien.Si vous utilisez Maven, vous pouvez facilement importer le fichier JAR dans votre application en ajoutant le code suivant au fichier pom.xml de votre projet.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Créer un formulaire à remplir dans Word en Java
La classe StructureDocumentTagInline fournie par Spire.Doc pour Java est utilisée pour créer des balises de document structuré pour les structures de niveau en ligne (objet DrawingML, champs, etc.) dans un paragraphe. La propriété SDTProperties et la propriété SDTContent sous cette classe doivent être utilisées pour spécifier les propriétés et le contenu de la balise de document structuré actuelle. Voici les étapes détaillées pour créer un formulaire à remplir avec des contrôles de contenu dans Word.
- Créez un objet Document.
- Ajoutez une section à l'aide de la méthode Document.addSection().
- Ajoutez une table à l’aide de la méthode Section.addTable().
- Ajoutez un paragraphe à une cellule de tableau spécifique à l’aide de la méthode TableCell.addParagraph().
- Créez une instance de la classe StructureDocumentTagInline et ajoutez-la au paragraphe en tant qu'objet enfant à l'aide de la méthode Paragraph.getChildObjects().add().
- Spécifiez les propriétés et le contenu de la balise de document structuré à l'aide des méthodes sous la propriété SDTProperties et la propriété SDTContent de l'objet StructureDocumentTagInline. Le type de balise de document structuré est défini via la méthode SDTProperties.setSDTType().
- Empêchez les utilisateurs de modifier le contenu en dehors des champs de formulaire à l'aide de la méthode Document.protect().
- Enregistrez le document à l'aide de la méthode Document.saveToFile().
- Java
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.DocPicture; import com.spire.doc.fields.TextRange; import java.util.Date; public class CreateFillableForm { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Add a section Section section = doc.addSection(); //add a table Table table = section.addTable(true); table.resetCells(7, 2); //Add text to the cells of the first column Paragraph paragraph = table.getRows().get(0).getCells().get(0).addParagraph(); paragraph.appendText("Plain Text Content Control"); paragraph = table.getRows().get(1).getCells().get(0).addParagraph(); paragraph.appendText("Rich Text Content Control"); paragraph = table.getRows().get(2).getCells().get(0).addParagraph(); paragraph.appendText("Picture Content Control"); paragraph = table.getRows().get(3).getCells().get(0).addParagraph(); paragraph.appendText("Drop-Down List Content Control"); paragraph = table.getRows().get(4).getCells().get(0).addParagraph(); paragraph.appendText("Check Box Content Control"); paragraph = table.getRows().get(5).getCells().get(0).addParagraph(); paragraph.appendText("Combo box Content Control"); paragraph = table.getRows().get(6).getCells().get(0).addParagraph(); paragraph.appendText("Date Picker Content Control"); //Add a plain text content control to the cell (0,1) paragraph = table.getRows().get(0).getCells().get(1).addParagraph(); StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc); paragraph.getChildObjects().add(sdt); sdt.getSDTProperties().setSDTType(SdtType.Text); sdt.getSDTProperties().setAlias("Plain Text"); sdt.getSDTProperties().setTag("Plain Text"); sdt.getSDTProperties().isShowingPlaceHolder(true); SdtText text = new SdtText(true); text.isMultiline(false); sdt.getSDTProperties().setControlProperties(text); TextRange tr = new TextRange(doc); tr.setText("Click or tap here to enter text."); sdt.getSDTContent().getChildObjects().add(tr); //Add a rich text content control to the cell (1,1) paragraph = table.getRows().get(1).getCells().get(1).addParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.getChildObjects().add(sdt); sdt.getSDTProperties().setSDTType(SdtType.Rich_Text); sdt.getSDTProperties().setAlias("Rich Text"); sdt.getSDTProperties().setTag("Rich Text"); sdt.getSDTProperties().isShowingPlaceHolder(true); text = new SdtText(true); text.isMultiline(false); sdt.getSDTProperties().setControlProperties(text); tr = new TextRange(doc); tr.setText("Click or tap here to enter text."); sdt.getSDTContent().getChildObjects().add(tr); //Add a picture content control to the cell (2,1) paragraph = table.getRows().get(2).getCells().get(1).addParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.getChildObjects().add(sdt); sdt.getSDTProperties().setSDTType(SdtType.Picture); sdt.getSDTProperties().setAlias("Picture"); sdt.getSDTProperties().setTag("Picture"); SdtPicture sdtPicture = new SdtPicture(); sdt.getSDTProperties().setControlProperties(sdtPicture); DocPicture pic = new DocPicture(doc); pic.loadImage("C:\\Users\\Administrator\\Desktop\\ChooseImage.png"); sdt.getSDTContent().getChildObjects().add(pic); //Add a dropdown list content control to the cell(3,1) paragraph = table.getRows().get(3).getCells().get(1).addParagraph(); sdt = new StructureDocumentTagInline(doc); sdt.getSDTProperties().setSDTType(SdtType.Drop_Down_List); sdt.getSDTProperties().setAlias("Dropdown List"); sdt.getSDTProperties().setTag("Dropdown List"); paragraph.getChildObjects().add(sdt); SdtDropDownList sddl = new SdtDropDownList(); sddl.getListItems().add(new SdtListItem("Choose an item.", "1")); sddl.getListItems().add(new SdtListItem("Item 2", "2")); sddl.getListItems().add(new SdtListItem("Item 3", "3")); sddl.getListItems().add(new SdtListItem("Item 4", "4")); sdt.getSDTProperties().setControlProperties(sddl); tr = new TextRange(doc); tr.setText(sddl.getListItems().get(0).getDisplayText()); sdt.getSDTContent().getChildObjects().add(tr); //Add two check box content controls to the cell (4,1) paragraph = table.getRows().get(4).getCells().get(1).addParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.getChildObjects().add(sdt); sdt.getSDTProperties().setSDTType(SdtType.Check_Box); SdtCheckBox scb = new SdtCheckBox(); sdt.getSDTProperties().setControlProperties(scb); tr = new TextRange(doc); sdt.getChildObjects().add(tr); scb.setChecked(false); paragraph.appendText(" Option 1"); paragraph = table.getRows().get(4).getCells().get(1).addParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.getChildObjects().add(sdt); sdt.getSDTProperties().setSDTType(SdtType.Check_Box); scb = new SdtCheckBox(); sdt.getSDTProperties().setControlProperties(scb); tr = new TextRange(doc); sdt.getChildObjects().add(tr); scb.setChecked(false); paragraph.appendText(" Option 2"); //Add a combo box content control to the cell (5,1) paragraph = table.getRows().get(5).getCells().get(1).addParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.getChildObjects().add(sdt); sdt.getSDTProperties().setSDTType(SdtType.Combo_Box); sdt.getSDTProperties().setAlias("Combo Box"); sdt.getSDTProperties().setTag("Combo Box"); SdtComboBox cb = new SdtComboBox(); cb.getListItems().add(new SdtListItem("Choose an item.")); cb.getListItems().add(new SdtListItem("Item 2")); cb.getListItems().add(new SdtListItem("Item 3")); sdt.getSDTProperties().setControlProperties(cb); tr = new TextRange(doc); tr.setText(cb.getListItems().get(0).getDisplayText()); sdt.getSDTContent().getChildObjects().add(tr); //Add a date picker content control to the cell (6,1) paragraph = table.getRows().get(6).getCells().get(1).addParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.getChildObjects().add(sdt); sdt.getSDTProperties().setSDTType(SdtType.Date_Picker); sdt.getSDTProperties().setAlias("Date Picker"); sdt.getSDTProperties().setTag("Date Picker"); SdtDate date = new SdtDate(); date.setCalendarType(CalendarType.Default); date.setDateFormat("yyyy.MM.dd"); date.setFullDate(new Date()); sdt.getSDTProperties().setControlProperties(date); tr = new TextRange(doc); tr.setText("Click or tap to enter a date."); sdt.getSDTContent().getChildObjects().add(tr); //Allow users to edit the form fields only doc.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd"); //Save to file doc.saveToFile("output/WordForm.docx", FileFormat.Docx_2013); } }
Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
Java Proteger o Desproteger Documentos de Word
Tabla de contenido
- Instalar Spire.Doc for Java
- Proteger un documento de Word con una contraseña en Java
- Cambiar permiso de un documento de Word en Java
- Bloquear secciones específicas de un documento de Word en Java
- Marcar un documento de Word como final en Java
- Eliminar contraseña de un documento de Word cifrado en Java
- Ver también
Instalar con Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
enlaces relacionados
Habilitar las opciones de seguridad de sus documentos de Word es esencial para mantener segura la información confidencial. Puede cifra tu documento con una contraseña para que no pueda ser abierto por usuarios no autorizados; puede habilitar el modo de solo lectura impedir que los usuarios cambien el contenido; tú también puedes restringir parcialmente la edición de su documento. Este artículo demuestra cómo proteger o desproteger documentos de Word en Java utilizando Spire.Doc for Java.
- Proteger un documento de Word con una contraseña en Java
- Cambiar permiso de un documento de Word en Java
- Bloquear secciones específicas de un documento de Word en Java
- Marcar un documento de Word como final en Java
- Eliminar contraseña de un documento de Word cifrado en Java
Instalar Spire.Doc for Java
En primer lugar, debe agregar el archivo Spire.Doc.jar como una dependencia en su programa Java. El archivo JAR se puede descargar desde este enlace.Si usa Maven, puede importar fácilmente el archivo JAR en su aplicación agregando el siguiente código al archivo pom.xml de su proyecto.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Proteger un documento de Word con una contraseña en Java
Cifrar un documento con una contraseña garantiza que solo usted y determinadas personas puedan leerlo o editarlo. Los siguientes son los pasos para proteger con contraseña un documento de Word usando Spire.Doc for Java.
- Crea un objeto de documento.
- Cargue un documento de Word utilizando el método Document.loadFromFile().
- Cifre el documento con una contraseña utilizando el método Document.encrypt().
- Guarde el documento en otro archivo de Word utilizando el método Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class PasswordProtectWord { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Encrypt the document with a password document.encrypt("open-psd"); //Save the document to another Word file document.saveToFile("output/Encryption.docx", FileFormat.Docx); } }
Cambiar permiso de un documento de Word en Java
Los documentos cifrados con una contraseña abierta no pueden ser abiertos por quienes no conocen la contraseña. Si desea otorgar permiso a las personas para leer su documento pero restringir los tipos de modificaciones que alguien puede realizar, puede configurar el permiso del documento. Los siguientes son los pasos para cambiar el permiso de un documento de Word usando Spire.Doc for Java.
- Crea un objeto de documento.
- Cargue un documento de Word utilizando el método Document.loadFromFile().
- Establezca el permiso del documento y la contraseña del permiso utilizando el método Document.protect().
- Guarde el documento en otro archivo de Word utilizando el método Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class ChangePermission { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set the document permission and set the permission password document.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd"); //Save the document to another Word file document.saveToFile("output/Permission.docx"); } }
Bloquear secciones específicas de un documento de Word en Java
Puede bloquear partes de su documento de Word para que no se puedan cambiar y dejar las partes desbloqueadas disponibles para editar. Los siguientes son los pasos para proteger secciones específicas de un documento de Word usando Spire.Doc for Java.
- Crea un objeto de documento.
- Cargue un documento de Word utilizando el método Document.loadFromFile().
- Establezca la restricción de edición como Allow_Only_Form_Fields.
- Desproteja una sección específica pasando false a Sección.protectForm() como parámetro. El resto de tramos seguirán protegidos.
- Guarde el documento en otro archivo de Word utilizando el método Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class LockSpecificSections { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set editing restriction as "Allow_Only_Form_Fields" doc.protect(ProtectionType.Allow_Only_Form_Fields, "permissionPsd"); //Unprotect section 2 doc.getSections().get(1).setProtectForm(false); //Save the document to another Word file doc.saveToFile("output/ProtectSection.docx"); } }
Marcar un documento de Word como final en Java
Al marcar un documento como Final, deshabilita las capacidades de escritura, edición y cambios de formato y aparecerá un mensaje a cualquier lector indicando que el documento ha sido finalizado. Los siguientes son los pasos para marcar un documento de Word como final usando Spire.Doc for Java.
- Crea un objeto de documento.
- Cargue un archivo de Word usando el método Document.loadFromFile().
- Obtenga el objeto CustomDocumentProperties del documento.
- Agregue una propiedad personalizada "_MarkAsFinal" al documento.
- Guarde el documento en otro archivo de Word utilizando el método Document.saveToFile().
- Java
import com.spire.doc.CustomDocumentProperties; import com.spire.doc.Document; public class MarkAsFinal { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Get custom document properties CustomDocumentProperties customProperties = doc.getCustomDocumentProperties(); //Add "_MarkAsFinal" as a property to the document customProperties.add("_MarkAsFinal", true); //Save the document to another Word file doc.saveToFile("output/MarkAsFinal.docx"); } }
Eliminar contraseña de un documento de Word cifrado en Java
Puede eliminar la contraseña de un documento cifrado si el cifrado ya no es necesario. Los siguientes son los pasos detallados.
- Crea un objeto de documento.
- Cargue un documento de Word utilizando el método Document.loadFromFile().
- Elimine la contraseña utilizando el método Document.removeEncryption().
- Guarde el documento en otro archivo de Word utilizando el método Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class RemovePassword { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load an encrypted Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat.Docx, "open-psd"); //Remove encryption document.removeEncryption(); //Save the document to another Word file document.saveToFile("output/RemoveEncryption.docx", FileFormat.Docx); } }
Solicite una licencia temporal
Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.
Java Protect or Unprotect Word Documents
Table of Contents
Install with Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
Related Links
If you're interested in exploring opportunities in Java programming language, you can find various developer jobs that require expertise in document security and manipulation. |
Enabling security options of your Word documents is essential for keeping sensitive information safe. You can encrypt your document with a password so that it cannot be opened by unauthorized users; you can enable the Read-only mode to prevent users from changing the content; you can also partially restrict editing your document. This article demonstrates how to protect or unprotect Word documents in Java using Spire.Doc for Java.
- Protect a Word Document with a Password in Java
- Change Permission of a Word Document in Java
- Lock Specified Sections of a Word Document in Java
- Mark a Word Document as Final in Java
- Remove Password from an Encrypted Word Document in Java
Install Spire.Doc for Java
First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Protect a Word Document with a Password in Java
Encrypting a document with a password makes sure that only you and certain people can read or edit it. The following are the steps to password protect a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Encrypt the document with a password using Document.encrypt() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class PasswordProtectWord { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Encrypt the document with a password document.encrypt("open-psd"); //Save the document to another Word file document.saveToFile("output/Encryption.docx", FileFormat.Docx); } }
Change Permission of a Word Document in Java
Documents encrypted with an open password cannot be opened by those who do not know the password. If you’d like to grant people permission to read your document but restrict the types of modifications that someone can make, you can set the document permission. The following are the steps to change permission of a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Set the document permission and the permission password using Document.protect() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class ChangePermission { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set the document permission and set the permission password document.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd"); //Save the document to another Word file document.saveToFile("output/Permission.docx"); } }
Lock Specified Sections of a Word Document in Java
You can lock parts of your Word document so that they cannot be changed and leave the unlocked parts available for editing. The following are the steps to protect specified sections of a Word document using Spire.Doc for Java.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Set the editing restriction as Allow_Only_Form_Fields.
- Unprotect a specific section by passing false to Section.protectForm() as a parameter. The rest sections will continue to be protected.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class LockSpecificSections { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set editing restriction as "Allow_Only_Form_Fields" doc.protect(ProtectionType.Allow_Only_Form_Fields, "permissionPsd"); //Unprotect section 2 doc.getSections().get(1).setProtectForm(false); //Save the document to another Word file doc.saveToFile("output/ProtectSection.docx"); } }
Mark a Word Document as Final in Java
By marking a document as Final, you disable typing, editing, and format changes capabilities and a message will appear to any reader that the document has been finalized. The following are the steps to mark a Word document as final using Spire.Doc for Java.
- Create a Document object.
- Load a Word file using Document.loadFromFile() method.
- Get the CustomDocumentProperties object from the document.
- Add a custom property "_MarkAsFinal" to the document.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.CustomDocumentProperties; import com.spire.doc.Document; public class MarkAsFinal { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Get custom document properties CustomDocumentProperties customProperties = doc.getCustomDocumentProperties(); //Add "_MarkAsFinal" as a property to the document customProperties.add("_MarkAsFinal", true); //Save the document to another Word file doc.saveToFile("output/MarkAsFinal.docx"); } }
Remove Password from an Encrypted Word Document in Java
You can remove the password from an encrypted document if the encryption is no longer needed. The following are the detailed steps.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Remove the password using Document.removeEncryption() method.
- Save the document to another Word file using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class RemovePassword { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load an encrypted Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat.Docx, "open-psd"); //Remove encryption document.removeEncryption(); //Save the document to another Word file document.saveToFile("output/RemoveEncryption.docx", FileFormat.Docx); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java proteger ou desproteger documentos do Word
Índice
- Instale Spire.Doc for Java
- Proteja um documento do Word com uma senha em Java
- Alterar permissão de um documento do Word em Java
- Bloquear seções especificadas de um documento do Word em Java
- Marcar um documento do Word como final em Java
- Remover a senha de um documento do Word criptografado em Java
- Veja também
Instalar com Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
Links Relacionados
Habilitar opções de segurança em seus documentos do Word é essencial para manter informações confidenciais seguras. Você pode criptografe seu documento com uma senha para que não possa ser aberto por usuários não autorizados; você pode ativar o modo somente leitura impedir que os usuários alterem o conteúdo; você também pode restringir parcialmente a edição do seu documento. Este artigo demonstra como proteger ou desproteger documentos do Word em Java usando Spire.Doc for Java.
- Proteja um documento do Word com uma senha em Java
- Alterar permissão de um documento do Word em Java
- Bloquear seções especificadas de um documento do Word em Java
- Marcar um documento do Word como final em Java
- Remover a senha de um documento do Word criptografado em Java
Instale Spire.Doc for Java
Primeiro de tudo, você deve adicionar o arquivo Spire.Doc.jar como uma dependência em seu programa Java. O arquivo JAR pode ser baixado neste link.Se você usa Maven, pode importar facilmente o arquivo JAR em seu aplicativo adicionando o código a seguir ao arquivo pom.xml do seu projeto.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Proteja um documento do Word com uma senha em Java
Criptografar um documento com uma senha garante que somente você e determinadas pessoas possam lê-lo ou editá-lo. A seguir estão as etapas para proteger com senha um documento do Word usando Spire.Doc for Java.
- Crie um objeto Documento.
- Carregue um documento do Word usando o método Document.loadFromFile().
- Criptografe o documento com uma senha usando o método Document.encrypt().
- Salve o documento em outro arquivo do Word usando o método Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class PasswordProtectWord { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Encrypt the document with a password document.encrypt("open-psd"); //Save the document to another Word file document.saveToFile("output/Encryption.docx", FileFormat.Docx); } }
Alterar permissão de um documento do Word em Java
Documentos criptografados com senha aberta não podem ser abertos por quem não conhece a senha. Se desejar conceder permissão às pessoas para lerem seu documento, mas restringir os tipos de modificações que alguém pode fazer, você pode definir a permissão do documento. A seguir estão as etapas para alterar a permissão de um documento do Word usando Spire.Doc for Java.
- Crie um objeto Documento.
- Carregue um documento do Word usando o método Document.loadFromFile().
- Defina a permissão do documento e a senha de permissão usando o método Document.protect().
- Salve o documento em outro arquivo do Word usando o método Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class ChangePermission { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set the document permission and set the permission password document.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd"); //Save the document to another Word file document.saveToFile("output/Permission.docx"); } }
Bloquear seções especificadas de um documento do Word em Java
Você pode bloquear partes do seu documento do Word para que não possam ser alteradas e deixar as partes desbloqueadas disponíveis para edição. A seguir estão as etapas para proteger seções específicas de um documento do Word usando Spire.Doc for Java.
- Crie um objeto Documento.
- Carregue um documento do Word usando o método Document.loadFromFile().
- Defina a restrição de edição como Allow_Only_Form_Fields.
- Desproteja uma seção específica passando false para Section.protectForm() como parâmetro. As demais seções continuarão protegidas.
- Salve o documento em outro arquivo do Word usando o método Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class LockSpecificSections { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set editing restriction as "Allow_Only_Form_Fields" doc.protect(ProtectionType.Allow_Only_Form_Fields, "permissionPsd"); //Unprotect section 2 doc.getSections().get(1).setProtectForm(false); //Save the document to another Word file doc.saveToFile("output/ProtectSection.docx"); } }
Marcar um documento do Word como final em Java
Ao marcar um documento como Final, você desativa os recursos de digitação, edição e alterações de formato e uma mensagem aparecerá para qualquer leitor informando que o documento foi finalizado. A seguir estão as etapas para marcar um documento do Word como final usando Spire.Doc for Java.
- Crie um objeto Documento.
- Carregue um arquivo Word usando o método Document.loadFromFile().
- Obtenha o objeto CustomDocumentProperties do documento.
- Adicione uma propriedade customizada "_MarkAsFinal" ao documento.
- Salve o documento em outro arquivo do Word usando o método Document.saveToFile().
- Java
import com.spire.doc.CustomDocumentProperties; import com.spire.doc.Document; public class MarkAsFinal { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Get custom document properties CustomDocumentProperties customProperties = doc.getCustomDocumentProperties(); //Add "_MarkAsFinal" as a property to the document customProperties.add("_MarkAsFinal", true); //Save the document to another Word file doc.saveToFile("output/MarkAsFinal.docx"); } }
Remover a senha de um documento do Word criptografado em Java
Você poderá remover a senha de um documento criptografado se a criptografia não for mais necessária. A seguir estão as etapas detalhadas.
- Crie um objeto Documento.
- Carregue um documento do Word usando o método Document.loadFromFile().
- Remova a senha usando o método Document.removeEncryption().
- Salve o documento em outro arquivo do Word usando o método Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class RemovePassword { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load an encrypted Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat.Docx, "open-psd"); //Remove encryption document.removeEncryption(); //Save the document to another Word file document.saveToFile("output/RemoveEncryption.docx", FileFormat.Docx); } }
Solicite uma licença temporária
Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
Защита или снятие защиты Java с документов Word
Оглавление
Установить с помощью Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
Ссылки по теме
Включение параметров безопасности ваших документов Word необходимо для обеспечения безопасности конфиденциальной информации. Ты можешь зашифруйте свой документ паролем чтобы его не могли открыть неавторизованные пользователи; ты можешь включить режим «Только чтение» запретить пользователям изменять контент; ты также можешь частично ограничить редактирование документа. В этой статье показано, как защитить или снять защиту документов Word в Java с помощью Spire.Doc for Java.
- Защитите документ Word паролем в Java
- Изменение разрешения документа Word в Java
- Блокировка указанных разделов документа Word в Java
- Пометить документ Word как окончательный в Java
- Удалить пароль из зашифрованного документа Word на Java
Установите Spire.Doc for Java
Прежде всего, вам необходимо добавить файл Spire.Doc.jar в качестве зависимости в вашу Java-программу. JAR-файл можно скачать по этой ссылке.Если вы используете Maven, вы можете легко импортировать файл JAR в свое приложение, добавив следующий код в файл pom.xml вашего проекта.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Защитите документ Word паролем в Java
Шифрование документа с помощью пароля гарантирует, что только вы и определенные люди смогут его читать или редактировать. Ниже приведены шаги по защите паролем документа Word с помощью Spire.Doc for Java.
- Создайте объект Документ.
- Загрузите документ Word с помощью метода Document.loadFromFile().
- Зашифруйте документ паролем, используя метод Document.encrypt().
- Сохраните документ в другой файл Word, используя метод Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class PasswordProtectWord { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Encrypt the document with a password document.encrypt("open-psd"); //Save the document to another Word file document.saveToFile("output/Encryption.docx", FileFormat.Docx); } }
Изменение разрешения документа Word в Java
Документы, зашифрованные открытым паролем, не могут быть открыты теми, кто не знает пароля. Если вы хотите предоставить людям разрешение на чтение вашего документа, но ограничить типы изменений, которые кто-либо может внести, вы можете установить разрешение документа. Ниже приведены шаги по изменению разрешения документа Word с помощью Spire.Doc for Java.
- Создайте объект Документ.
- Загрузите документ Word с помощью метода Document.loadFromFile().
- Установите разрешение документа и пароль разрешения, используя метод Document.protect().
- Сохраните документ в другой файл Word, используя метод Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class ChangePermission { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set the document permission and set the permission password document.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd"); //Save the document to another Word file document.saveToFile("output/Permission.docx"); } }
Блокировка указанных разделов документа Word в Java
Вы можете заблокировать части документа Word, чтобы их нельзя было изменить, а незаблокированные части оставить доступными для редактирования. Ниже приведены шаги по защите определенных разделов документа Word с помощью Spire.Doc for Java.
- Создайте объект Документ.
- Загрузите документ Word с помощью метода Document.loadFromFile().
- SУстановите ограничение редактирования как Allow_Only_Form_Fields.
- Снимите защиту с определенного раздела, передав false в раздел.protectForm() в качестве параметра. Остальные разделы по-прежнему будут защищены.
- Сохраните документ в другой файл Word, используя метод Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class LockSpecificSections { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set editing restriction as "Allow_Only_Form_Fields" doc.protect(ProtectionType.Allow_Only_Form_Fields, "permissionPsd"); //Unprotect section 2 doc.getSections().get(1).setProtectForm(false); //Save the document to another Word file doc.saveToFile("output/ProtectSection.docx"); } }
Пометить документ Word как окончательный в Java
Помечая документ как окончательный, вы отключаете возможности ввода, редактирования и изменения формата, и любому читателю появится сообщение о том, что документ завершен. Ниже приведены шаги, позволяющие пометить документ Word как окончательный с помощью Spire.Doc for Java.
- Создайте объект Документ.
- Загрузите файл Word с помощью метода Document.loadFromFile().
- Получите объект CustomDocumentProperties из документа.
- Добавьте в документ пользовательское свойство «_MarkAsFinal».
- Сохраните документ в другой файл Word, используя метод Document.saveToFile().
- Java
import com.spire.doc.CustomDocumentProperties; import com.spire.doc.Document; public class MarkAsFinal { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Get custom document properties CustomDocumentProperties customProperties = doc.getCustomDocumentProperties(); //Add "_MarkAsFinal" as a property to the document customProperties.add("_MarkAsFinal", true); //Save the document to another Word file doc.saveToFile("output/MarkAsFinal.docx"); } }
Удалить пароль из зашифрованного документа Word на Java
Вы можете удалить пароль из зашифрованного документа, если шифрование больше не требуется. Ниже приведены подробные шаги.
- Создайте объект Документ.
- Загрузите документ Word с помощью метода Document.loadFromFile().
- Удалите пароль с помощью метода Document.removeEncryption().
- Сохраните документ в другой файл Word, используя метод Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class RemovePassword { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load an encrypted Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat.Docx, "open-psd"); //Remove encryption document.removeEncryption(); //Save the document to another Word file document.saveToFile("output/RemoveEncryption.docx", FileFormat.Docx); } }
Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста, запросите 30-дневную пробную лицензию для себя.
Java 보호 또는 Word 문서 보호 해제
목차
메이븐으로 설치
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
관련된 링크들
민감한 정보를 안전하게 유지하려면 Word 문서의 보안 옵션을 활성화하는 것이 필수적입니다. 당신은 할 수 있습니다 비밀번호로 문서를 암호화하세요 승인되지 않은 사용자가 열 수 없도록; 당신은 할 수 읽기 전용 모드 활성화 사용자가 콘텐츠를 변경하는 것을 방지합니다. 당신은 또한 수 문서 편집을 부분적으로 제한합니다.. 이 문서에서는 다음 방법을 보여줍니다 Java에서 Word 문서 보호 또는 보호 해제 Spire.Doc for Java 사용합니다.
- Java에서 비밀번호로 Word 문서 보호
- Java에서 Word 문서의 권한 변경
- Java에서 Word 문서의 지정된 섹션 잠금
- Java에서 Word 문서를 최종 문서로 표시
- Java의 암호화된 Word 문서에서 비밀번호 제거
Spire.Doc for Java 설치
우선, Spire.Doc.jar 파일을 Java 프로그램의 종속성으로 추가해야 합니다. JAR 파일은 이 링크에서 다운로드할 수 있습니다. Maven을 사용하는 경우 프로젝트의 pom.xml 파일에 다음 코드를 추가하여 애플리케이션에서 JAR 파일을 쉽게 가져올 수 있습니다.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Java에서 비밀번호로 Word 문서 보호
문서를 비밀번호로 암호화하면 귀하와 특정 사람들만이 문서를 읽거나 편집할 수 있습니다. 다음은 Spire.Doc for Java 사용하여 Word 문서를 비밀번호로 보호하는 단계입니다.
- 문서 개체를 만듭니다.
- Document.loadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.encrypt() 메서드를 사용하여 문서를 비밀번호로 암호화합니다.
- Document.saveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class PasswordProtectWord { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Encrypt the document with a password document.encrypt("open-psd"); //Save the document to another Word file document.saveToFile("output/Encryption.docx", FileFormat.Docx); } }
Java에서 Word 문서의 권한 변경
공개 비밀번호로 암호화된 문서는 비밀번호를 모르는 사람은 열 수 없습니다. 다른 사람에게 문서를 읽을 수 있는 권한을 부여하고 수정 가능한 유형을 제한하려는 경우 문서 권한을 설정할 수 있습니다. 다음은 Spire.Doc for Java를 사용하여 Word 문서의 권한을 변경하는 단계입니다.
- 문서 개체를 만듭니다.
- Document.loadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.protect() 메서드를 사용하여 문서 권한과 권한 비밀번호를 설정합니다.
- Document.saveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class ChangePermission { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set the document permission and set the permission password document.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd"); //Save the document to another Word file document.saveToFile("output/Permission.docx"); } }
Java에서 Word 문서의 지정된 섹션 잠금
Word 문서의 일부를 변경할 수 없도록 잠그고 잠금 해제된 부분은 편집할 수 있도록 남겨둘 수 있습니다. 다음은 Spire.Doc for Java 사용하여 Word 문서의 특정 섹션을 보호하는 단계입니다.
- 문서 개체를 만듭니다.
- Document.loadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- 편집 제한을 Allow_Only_Form_Fields로 설정합니다.
- Section.protectForm()에 false를 매개변수로 전달하여 특정 섹션의 보호를 해제합니다. 나머지 섹션은 계속해서 보호됩니다.
- Document.saveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class LockSpecificSections { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set editing restriction as "Allow_Only_Form_Fields" doc.protect(ProtectionType.Allow_Only_Form_Fields, "permissionPsd"); //Unprotect section 2 doc.getSections().get(1).setProtectForm(false); //Save the document to another Word file doc.saveToFile("output/ProtectSection.docx"); } }
Java에서 Word 문서를 최종 문서로 표시
문서를 최종본으로 표시하면 입력, 편집, 형식 변경 기능이 비활성화되고 모든 독자에게 문서가 완성되었다는 메시지가 표시됩니다. 다음은 Spire.Doc for Java 사용하여 Word 문서를 최종 문서로 표시하는 단계입니다.
- 문서 개체를 만듭니다.
- Document.loadFromFile() 메서드를 사용하여 Word 파일을 로드합니다.
- 문서에서 CustomDocumentProperties 개체를 가져옵니다.
- 문서에 사용자 정의 속성 "_MarkAsFinal"을 추가합니다.
- Document.saveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
- Java
import com.spire.doc.CustomDocumentProperties; import com.spire.doc.Document; public class MarkAsFinal { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Get custom document properties CustomDocumentProperties customProperties = doc.getCustomDocumentProperties(); //Add "_MarkAsFinal" as a property to the document customProperties.add("_MarkAsFinal", true); //Save the document to another Word file doc.saveToFile("output/MarkAsFinal.docx"); } }
Java의 암호화된 Word 문서에서 비밀번호 제거
암호화가 더 이상 필요하지 않은 경우 암호화된 문서에서 비밀번호를 제거할 수 있습니다. 자세한 단계는 다음과 같습니다.
- 문서 개체를 만듭니다.
- Document.loadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.removeEncryption() 메서드를 사용하여 비밀번호를 제거합니다.
- Document.saveToFile() 메서드를 사용하여 문서를 다른 Word 파일에 저장합니다.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class RemovePassword { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load an encrypted Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat.Docx, "open-psd"); //Remove encryption document.removeEncryption(); //Save the document to another Word file document.saveToFile("output/RemoveEncryption.docx", FileFormat.Docx); } }
임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
Java Proteggi o rimuovi la protezione dei documenti Word
Sommario
- Installa Spire.Doc for Java
- Proteggi un documento Word con una password in Java
- Modificare l'autorizzazione di un documento Word in Java
- Blocca sezioni specificate di un documento Word in Java
- Contrassegna un documento Word come finale in Java
- Rimuovi la password da un documento Word crittografato in Java
- Guarda anche
Installa con Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
Link correlati
Abilitare le opzioni di sicurezza dei tuoi documenti Word è essenziale per mantenere al sicuro le informazioni sensibili. Puoi crittografare il documento con una password in modo che non possa essere aperto da utenti non autorizzati; puoi abilitare la modalità di sola lettura impedire agli utenti di modificare il contenuto; Puoi anche limitare parzialmente la modifica del documento.. Questo articolo illustra come farlo proteggere o rimuovere la protezione dei documenti Word in Java utilizzando Spire.Doc for Java.
- Proteggi un documento Word con una password in Java
- Modificare l'autorizzazione di un documento Word in Java
- Blocca sezioni specificate di un documento Word in Java
- Contrassegna un documento Word come finale in Java
- Rimuovi la password da un documento Word crittografato in Java
Installa Spire.Doc for Java
Prima di tutto, devi aggiungere il file Spire.Doc.jar come dipendenza nel tuo programma Java. Il file JAR può essere scaricato da questo collegamento. Se utilizzi Maven, puoi importare facilmente il file JAR nella tua applicazione aggiungendo il seguente codice al file pom.xml del tuo progetto.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Proteggi un documento Word con una password in Java
La crittografia di un documento con una password garantisce che solo tu e determinate persone possiate leggerlo o modificarlo. Di seguito sono riportati i passaggi per proteggere con password un documento Word utilizzando Spire.Doc for Java.
- Creare un oggetto Documento.
- Carica un documento Word utilizzando il metodo Document.loadFromFile().
- Crittografa il documento con una password utilizzando il metodo Document.encrypt().
- Salva il documento in un altro file Word utilizzando il metodo Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class PasswordProtectWord { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Encrypt the document with a password document.encrypt("open-psd"); //Save the document to another Word file document.saveToFile("output/Encryption.docx", FileFormat.Docx); } }
Modificare l'autorizzazione di un documento Word in Java
I documenti crittografati con una password aperta non possono essere aperti da chi non conosce la password. Se desideri concedere alle persone l'autorizzazione a leggere il tuo documento ma limitare i tipi di modifiche che qualcuno può apportare, puoi impostare l'autorizzazione del documento. Di seguito sono riportati i passaggi per modificare l'autorizzazione di un documento Word utilizzando Spire.Doc for Java.
- Creare un oggetto Documento.
- Carica un documento Word utilizzando il metodo Document.loadFromFile().
- Imposta l'autorizzazione del documento e la password dell'autorizzazione utilizzando il metodo Document.protect().
- Salva il documento in un altro file Word utilizzando il metodo Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class ChangePermission { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load a Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set the document permission and set the permission password document.protect(ProtectionType.Allow_Only_Form_Fields, "permission-psd"); //Save the document to another Word file document.saveToFile("output/Permission.docx"); } }
Blocca sezioni specificate di un documento Word in Java
Puoi bloccare parti del tuo documento Word in modo che non possano essere modificate e lasciare le parti sbloccate disponibili per la modifica. Di seguito sono riportati i passaggi per proteggere sezioni specifiche di un documento Word utilizzando Spire.Doc for Java.
- Creare un oggetto Documento.
- Carica un documento Word utilizzando il metodo Document.loadFromFile().
- Imposta la restrizione di modifica su Always_Only_Form_Fields.
- Annulla la protezione di una sezione specifica passando false a Sezione.protectForm() come parametro. Le restanti sezioni continueranno ad essere protette.
- Salva il documento in un altro file Word utilizzando il metodo Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.ProtectionType; public class LockSpecificSections { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Set editing restriction as "Allow_Only_Form_Fields" doc.protect(ProtectionType.Allow_Only_Form_Fields, "permissionPsd"); //Unprotect section 2 doc.getSections().get(1).setProtectForm(false); //Save the document to another Word file doc.saveToFile("output/ProtectSection.docx"); } }
Contrassegna un documento Word come finale in Java
Contrassegnando un documento come Finale, disabiliti le funzionalità di digitazione, modifica e modifica del formato e a qualsiasi lettore verrà visualizzato un messaggio che informa che il documento è stato finalizzato. Di seguito sono riportati i passaggi per contrassegnare un documento Word come finale utilizzando Spire.Doc for Java.
- Creare un oggetto Documento.
- Carica un file Word utilizzando il metodo Document.loadFromFile().
- Ottieni l'oggetto CustomDocumentProperties dal documento.
- Aggiungi una proprietà personalizzata "_MarkAsFinal" al documento.
- Salva il documento in un altro file Word utilizzando il metodo Document.saveToFile().
- Java
import com.spire.doc.CustomDocumentProperties; import com.spire.doc.Document; public class MarkAsFinal { public static void main(String[] args) { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //Get custom document properties CustomDocumentProperties customProperties = doc.getCustomDocumentProperties(); //Add "_MarkAsFinal" as a property to the document customProperties.add("_MarkAsFinal", true); //Save the document to another Word file doc.saveToFile("output/MarkAsFinal.docx"); } }
Rimuovi la password da un documento Word crittografato in Java
È possibile rimuovere la password da un documento crittografato se la crittografia non è più necessaria. Di seguito sono riportati i passaggi dettagliati.
- Creare un oggetto Documento.
- Carica un documento Word utilizzando il metodo Document.loadFromFile().
- Rimuovere la password utilizzando il metodo Document.removeEncryption().
- Salva il documento in un altro file Word utilizzando il metodo Document.saveToFile().
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; public class RemovePassword { public static void main(String[] args) { //Create a Document object Document document = new Document(); //Load an encrypted Word document document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat.Docx, "open-psd"); //Remove encryption document.removeEncryption(); //Save the document to another Word file document.saveToFile("output/RemoveEncryption.docx", FileFormat.Docx); } }
Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.
Java Convert Word to Images (JPG, PNG and SVG)
Table of Contents
Install with Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
Related Links
There are many reasons why you might need to convert Word documents to images. For example, a lot of devices can open and display images directly without any special software, and when images are transmitted their content is difficult to be tampered with. In this article, you will learn how to convert Word to popular image formats such as JPG, PNG and SVG using Spire.Doc for Java.
- Convert Word to JPG in Java
- Convert Word to SVG in Java
- Convert Word to PNG with Customized Resolution
Install Spire.Doc for Java
First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Convert Word to JPG in Java
Spire.Doc for Java offers the Document.saveToImages() method to convert a whole Word document into individual BufferedImage images. Then, each BufferedImage can be saved as a BMP, EMF, JPEG, PNG, GIF, or WMF file. The following are the steps to convert Word to JPG using this library.
- Create a Document object.
- Load a Word document using Document.loadFromFile() method.
- Convert the document to BufferedImage images using Document.saveToImages() method.
- Loop through the image collection to get the specific one.
- Re-write the image with different color space.
- Write the BufferedImage to a JPG file.
- Java
import com.spire.doc.Document; import com.spire.doc.documents.ImageType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ConvertWordToJPG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Convert the whole document into individual buffered images BufferedImage[] images = doc.saveToImages(ImageType.Bitmap); //Loop through the images for (int i = 0; i < images.length; i++) { //Get the specific image BufferedImage image = images[i]; //Re-write the image with a different color space BufferedImage newImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); newImg.getGraphics().drawImage(image, 0, 0, null); //Write to a JPG file File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.jpg"), i)); ImageIO.write(newImg, "JPEG", file); } } }
Convert Word to SVG in Java
Using Spire.Doc for Java, you can save a Word document as a list of byte arrays. Each byte array can then be written as a SVG file. The detailed steps to convert Word to SVG are as follows.
- Create a Document object.
- Load a Word file using Document.loadFromFile() method.
- Save the document as a list of byte arrays using Document.saveToSVG() method.
- Loop through the items in the list to get a specific byte array.
- Write the byte array to a SVG file.
- Java
import com.spire.doc.Document; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; public class ConvertWordToSVG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Save the document as a list of byte arrays List<byte[]> svgBytes = doc.saveToSVG(); //Loop through the items in the list for (int i = 0; i < svgBytes.size(); i++) { //Get a specific byte array byte[] byteArray = svgBytes.get(i); //Specify the output file name String outputFile = String.format("Image-%d.svg", i); //Write the byte array to a SVG file try (FileOutputStream stream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\Images\\" + outputFile)) { stream.write(byteArray); } } } }
Convert Word to PNG with Customized Resolution
An image with higher resolution is generally more clear. You can customize the image resolution while converting Word to PNG by following the following steps.
- Create a Document object.
- Load a Word file using Document.loadFromFile() method.
- Convert the document to BufferedImage images with the specified resolution using Document.saveToImages() method.
- Loop through the image collection to get the specific one and save it as a PNG file.
- Java
import com.spire.doc.Document; import com.spire.doc.documents.ImageType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ConvertWordToPNG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Convert the whole document into individual buffered images with customized resolution BufferedImage[] images = doc.saveToImages(0, doc.getPageCount(), ImageType.Bitmap, 150, 150); //Loop through the images for (int i = 0; i < images.length; i++) { //Get the specific image BufferedImage image = images[i]; //Write to a PNG file File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.png"), i)); ImageIO.write(image, "PNG", file); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java converte Word em imagens (JPG, PNG e SVG)
Índice
Instalar com Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
Links Relacionados
Existem muitos motivos pelos quais você pode precisar converter documentos do Word em imagens. Por exemplo, muitos dispositivos podem abrir e exibir imagens diretamente, sem qualquer software especial, e quando as imagens são transmitidas, é difícil adulterar seu conteúdo. Neste artigo você aprenderá como converta Word em formatos de imagem populares como JPG, PNG e SVG usando Spire.Doc for Java.
- Converta Word para JPG em Java
- Converter Word em SVG em Java
- Converta Word em PNG com resolução personalizada
Instale Spire.Doc for Java
Primeiro, você precisa adicionar o arquivo Spire.Doc.jar como uma dependência em seu programa Java. O arquivo JAR pode ser baixado neste link. Se você usa Maven, pode importar facilmente o arquivo JAR em seu aplicativo adicionando o código a seguir ao arquivo pom.xml do seu projeto.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Converta Word para JPG em Java
Spire.Doc for Java oferece o método Document.saveToImages() para converter um documento Word inteiro em imagens BufferedImage individuais. Então, cada BufferedImage pode ser salvo como um arquivo BMP, EMF, JPEG, PNG, GIF ou WMF. A seguir estão as etapas para converter Word em JPG usando esta biblioteca.
- Crie um objeto Documento.
- Carregue um documento do Word usando o método Document.loadFromFile().
- Converta o documento em imagens BufferedImage usando o método Document.saveToImages().
- Percorra a coleção de imagens para obter aquela específica.
- Reescreva a imagem com espaço de cores diferente.
- Grave o BufferedImage em um arquivo JPG.
- Java
import com.spire.doc.Document; import com.spire.doc.documents.ImageType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ConvertWordToJPG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Convert the whole document into individual buffered images BufferedImage[] images = doc.saveToImages(ImageType.Bitmap); //Loop through the images for (int i = 0; i < images.length; i++) { //Get the specific image BufferedImage image = images[i]; //Re-write the image with a different color space BufferedImage newImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); newImg.getGraphics().drawImage(image, 0, 0, null); //Write to a JPG file File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.jpg"), i)); ImageIO.write(newImg, "JPEG", file); } } }
Converter Word em SVG em Java
Usando o Spire.Doc for Java, você pode salvar um documento do Word como uma lista de matrizes de bytes. Cada matriz de bytes pode então ser escrita como um arquivo SVG. As etapas detalhadas para converter Word em SVG são as seguintes.
- Crie um objeto Documento.
- Carregue um arquivo Word usando o método Document.loadFromFile().
- Salve o documento como uma lista de matrizes de bytes usando o método Document.saveToSVG().
- Percorra os itens da lista para obter uma matriz de bytes específica.
- Grave a matriz de bytes em um arquivo SVG.
- Java
import com.spire.doc.Document; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; public class ConvertWordToSVG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Save the document as a list of byte arrays List<byte[]> svgBytes = doc.saveToSVG(); //Loop through the items in the list for (int i = 0; i < svgBytes.size(); i++) { //Get a specific byte array byte[] byteArray = svgBytes.get(i); //Specify the output file name String outputFile = String.format("Image-%d.svg", i); //Write the byte array to a SVG file try (FileOutputStream stream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\Images\\" + outputFile)) { stream.write(byteArray); } } } }
Converta Word em PNG com resolução personalizada
Uma imagem com resolução mais alta geralmente é mais nítida. Você pode personalizar a resolução da imagem ao converter Word para PNG seguindo as etapas a seguir.
- Crie um objeto Documento.
- Carregue um arquivo Word usando o método Document.loadFromFile().
- Converta o documento em imagens BufferedImage com a resolução especificada usando o método Document.saveToImages().
- Percorra a coleção de imagens para obter aquela específica e salve-a como um arquivo PNG.
- Java
import com.spire.doc.Document; import com.spire.doc.documents.ImageType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ConvertWordToPNG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Convert the whole document into individual buffered images with customized resolution BufferedImage[] images = doc.saveToImages(0, doc.getPageCount(), ImageType.Bitmap, 150, 150); //Loop through the images for (int i = 0; i < images.length; i++) { //Get the specific image BufferedImage image = images[i]; //Write to a PNG file File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.png"), i)); ImageIO.write(image, "PNG", file); } } }
Solicite uma licença temporária
Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
Java конвертирует Word в изображения (JPG, PNG и SVG)
Оглавление
Установить с помощью Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.2.2</version> </dependency>
Ссылки по теме
Существует множество причин, по которым вам может потребоваться преобразовать документы Word в изображения. Например, многие устройства могут открывать и отображать изображения напрямую, без какого-либо специального программного обеспечения, а при передаче изображений их содержимое трудно подделать. В этой статье вы узнаете, как конвертировать Word в популярные форматы изображений например JPG, PNG и SVG с использованием Spire.Doc for Java.
- Преобразование Word в JPG в Java
- Преобразование Word в SVG в Java
- Преобразование Word в PNG с индивидуальным разрешением
Установите Spire.Doc for Java
Во-первых, вам необходимо добавить файл Spire.Doc.jar в качестве зависимости в вашу программу Java. JAR-файл можно скачать по этой ссылке.Если вы используете Maven, вы можете легко импортировать файл JAR в свое приложение, добавив следующий код в файл pom.xml вашего проекта.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc</artifactId> <version>12.11.0</version> </dependency> </dependencies>
Преобразование Word в JPG в Java
Spire.Doc for Java предлагает метод Document.saveToImages() для преобразования всего документа Word в отдельные изображения BufferedImage. Затем каждое BufferedImage можно сохранить в формате BMP, EMF, JPEG, PNG, GIF или WMF. Ниже приведены шаги по преобразованию Word в JPG с использованием этой библиотеки.
- Создайте объект Документ.
- Загрузите документ Word с помощью метода Document.loadFromFile().
- Преобразуйте документ в изображения BufferedImage с помощью метода Document.saveToImages().
- Просмотрите коллекцию изображений, чтобы найти конкретное.
- Перепишите изображение с другим цветовым пространством.
- Запишите BufferedImage в файл JPG.
- Java
import com.spire.doc.Document; import com.spire.doc.documents.ImageType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ConvertWordToJPG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Convert the whole document into individual buffered images BufferedImage[] images = doc.saveToImages(ImageType.Bitmap); //Loop through the images for (int i = 0; i < images.length; i++) { //Get the specific image BufferedImage image = images[i]; //Re-write the image with a different color space BufferedImage newImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); newImg.getGraphics().drawImage(image, 0, 0, null); //Write to a JPG file File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.jpg"), i)); ImageIO.write(newImg, "JPEG", file); } } }
Преобразование Word в SVG в Java
Используя Spire.Doc for Java, вы можете сохранить документ Word в виде списка массивов байтов. Каждый массив байтов затем можно записать в виде файла SVG. Подробные шаги по преобразованию Word в SVG следующие.
- Создайте объект Документ.
- Загрузите файл Word с помощью метода Document.loadFromFile().
- Сохраните документ как список массивов байтов, используя метод Document.saveToSVG().
- Перебирайте элементы в списке, чтобы получить определенный массив байтов.
- Запишите массив байтов в файл SVG.
- Java
import com.spire.doc.Document; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; public class ConvertWordToSVG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Save the document as a list of byte arrays List<byte[]> svgBytes = doc.saveToSVG(); //Loop through the items in the list for (int i = 0; i < svgBytes.size(); i++) { //Get a specific byte array byte[] byteArray = svgBytes.get(i); //Specify the output file name String outputFile = String.format("Image-%d.svg", i); //Write the byte array to a SVG file try (FileOutputStream stream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\Images\\" + outputFile)) { stream.write(byteArray); } } } }
Преобразование Word в PNG с индивидуальным разрешением
Изображение с более высоким разрешением обычно более четкое. Вы можете настроить разрешение изображения при преобразовании Word в PNG, выполнив следующие действия.
- Создайте объект Документ.
- Загрузите файл Word с помощью метода Document.loadFromFile().
- Преобразуйте документ в изображения BufferedImage с указанным разрешением с помощью метода Document.saveToImages().
- Просмотрите коллекцию изображений, чтобы найти конкретное изображение, и сохраните его как файл PNG.
- Java
import com.spire.doc.Document; import com.spire.doc.documents.ImageType; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ConvertWordToPNG { public static void main(String[] args) throws IOException { //Create a Document object Document doc = new Document(); //Load a Word document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\ConvertTemplate.docx"); //Convert the whole document into individual buffered images with customized resolution BufferedImage[] images = doc.saveToImages(0, doc.getPageCount(), ImageType.Bitmap, 150, 150); //Loop through the images for (int i = 0; i < images.length; i++) { //Get the specific image BufferedImage image = images[i]; //Write to a PNG file File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.png"), i)); ImageIO.write(image, "PNG", file); } } }
Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.