Включение параметров безопасности ваших документов Word необходимо для обеспечения безопасности конфиденциальной информации. Ты можешь зашифруйте свой документ паролем чтобы его не могли открыть неавторизованные пользователи; ты можешь включить режим «Только чтение» запретить пользователям изменять контент; ты также можешь частично ограничить редактирование документа. В этой статье показано, как защитить или снять защиту документов Word в Java с помощью Spire.Doc for 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>14.2.4</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);
        }
    }

Java: Protect or Unprotect Word Documents

Изменение разрешения документа 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");
        }
    }

Java: Protect or Unprotect Word Documents

Блокировка указанных разделов документа 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");
        }
    }

Java: Protect or Unprotect Word Documents

Пометить документ 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");
        }
    }

Java: Protect or Unprotect Word Documents

Удалить пароль из зашифрованного документа 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-дневную пробную лицензию для себя.

Смотрите также

Monday, 06 November 2023 09:21

Java 보호 또는 Word 문서 보호 해제

민감한 정보를 안전하게 유지하려면 Word 문서의 보안 옵션을 활성화하는 것이 필수적입니다. 당신은 할 수 있습니다 비밀번호로 문서를 암호화하세요 승인되지 않은 사용자가 열 수 없도록; 당신은 할 수 읽기 전용 모드 활성화 사용자가 콘텐츠를 변경하는 것을 방지합니다. 당신은 또한 수 문서 편집을 부분적으로 제한합니다.. 이 문서에서는 다음 방법을 보여줍니다 Java에서 Word 문서 보호 또는 보호 해제 Spire.Doc for Java 사용합니다.

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>14.2.4</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: Protect or Unprotect Word Documents

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: Protect or Unprotect Word Documents

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: Protect or Unprotect Word Documents

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: Protect or Unprotect Word Documents

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일 평가판 라이센스 요청 자신을 위해.

또한보십시오

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.

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>14.2.4</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);
        }
    }

Java: Protect or Unprotect Word Documents

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");
        }
    }

Java: Protect or Unprotect Word Documents

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");
        }
    }

Java: Protect or Unprotect Word Documents

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");
        }
    }

Java: Protect or Unprotect Word Documents

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.

Guarda anche

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.

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>14.2.4</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);
            }
        }
    }

Java: Convert Word to Images (JPG, PNG and SVG)

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.

See Also

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.

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>14.2.4</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);
            }
        }
    }

Java: Convert Word to Images (JPG, PNG and SVG)

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.

Veja também

Установить с помощью 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.

Установите 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>14.2.4</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);
            }
        }
    }

Java: Convert Word to Images (JPG, PNG and SVG)

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также

Mit Maven installieren

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

verwandte Links

Es gibt viele Gründe, warum Sie Word-Dokumente in Bilder konvertieren müssen. Beispielsweise können viele Geräte Bilder ohne spezielle Software direkt öffnen und anzeigen, und wenn Bilder übertragen werden, ist es schwierig, deren Inhalt zu manipulieren. In diesem Artikel erfahren Sie, wie das geht Konvertieren Sie Word in gängige Bildformate wie JPG, PNG und SVG mit Spire.Doc for Java.

Installieren Sie Spire.Doc for Java

Zunächst müssen Sie die Datei Spire.Doc.jar als Abhängigkeit zu Ihrem Java-Programm hinzufügen. Die JAR-Datei kann über diesen Linkheruntergeladen werden. Wenn Sie Maven verwenden, können Sie die JAR-Datei einfach in Ihre Anwendung importieren, indem Sie den folgenden Code zur pom.xml-Datei Ihres Projekts hinzufügen.

<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>14.2.4</version>
    </dependency>
</dependencies>

Konvertieren Sie Word in Java in JPG

Spire.Doc for Java bietet die Methode Document.saveToImages() zum Konvertieren eines gesamten Word-Dokuments in einzelne BufferedImage-Bilder. Anschließend kann jedes BufferedImage als BMP-, EMF-, JPEG-, PNG-, GIF- oder WMF-Datei gespeichert werden. Im Folgenden finden Sie die Schritte zum Konvertieren von Word in JPG mithilfe dieser Bibliothek.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.loadFromFile().
  • Konvertieren Sie das Dokument mit der Methode Document.saveToImages() in BufferedImage-Bilder.
  • Durchlaufen Sie die Bildsammlung, um das spezifische Bild zu erhalten.
  • Schreiben Sie das Bild mit einem anderen Farbraum neu.
  • Schreiben Sie das BufferedImage in eine JPG-Datei.
  • 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);
            }
        }
    }

Konvertieren Sie Word in Java in SVG

Mit Spire.Doc for Java können Sie ein Word-Dokument als Liste von Byte-Arrays speichern. Jedes Byte-Array kann dann als SVG-Datei geschrieben werden. Die detaillierten Schritte zum Konvertieren von Word in SVG sind wie folgt.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Word-Datei mit der Methode Document.loadFromFile().
  • Speichern Sie das Dokument als Liste von Byte-Arrays mit der Methode Document.saveToSVG().
  • Durchlaufen Sie die Elemente in der Liste, um ein bestimmtes Byte-Array zu erhalten.
  • Schreiben Sie das Byte-Array in eine SVG-Datei.
  • 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);
                }
            }
        }
    }

Konvertieren Sie Word mit benutzerdefinierter Auflösung in PNG

Ein Bild mit höherer Auflösung ist im Allgemeinen klarer. Sie können die Bildauflösung beim Konvertieren von Word in PNG anpassen, indem Sie die folgenden Schritte ausführen.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Word-Datei mit der Methode Document.loadFromFile().
  • Konvertieren Sie das Dokument mit der Methode Document.saveToImages() in BufferedImage-Bilder mit der angegebenen Auflösung.
  • Durchlaufen Sie die Bildsammlung, um das spezifische Bild zu erhalten, und speichern Sie es als PNG-Datei.
  • 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);
            }
        }
    }

Java: Convert Word to Images (JPG, PNG and SVG)

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Instalar con Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

enlaces relacionados

Hay muchas razones por las que es posible que necesites convertir documentos de Word en imágenes. Por ejemplo, muchos dispositivos pueden abrir y mostrar imágenes directamente sin ningún software especial, y cuando se transmiten imágenes, es difícil alterar su contenido. En este artículo, aprenderá cómo convertir Word a formatos de imagen populares como JPG, PNG y SVG usando Spire.Doc for Java.

Instalar Spire.Doc for Java

Primero, 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>14.2.4</version>
    </dependency>
</dependencies>

Convertir Word a JPG en Java

Spire.Doc for Java ofrece el método Document.saveToImages() para convertir un documento completo de Word en imágenes BufferedImage individuales. Luego, cada BufferedImage se puede guardar como un archivo BMP, EMF, JPEG, PNG, GIF, o WMF. Los siguientes son los pasos para convertir Word a JPG usando esta biblioteca.

  • Crea un objeto de documento.
  • Cargue un documento de Word utilizando el método Document.loadFromFile().
  • Convierta el documento en imágenes BufferedImage utilizando el método Document.saveToImages().
  • Recorra la colección de imágenes para obtener la específica.
  • Vuelva a escribir la imagen con un espacio de color diferente.
  • Escriba la imagen almacenada en un archivo 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);
            }
        }
    }

Convertir Word a SVG en Java

Con Spire.Doc for Java, puede guardar un documento de Word como una lista de matrices de bytes. Luego, cada matriz de bytes se puede escribir como un archivo SVG. Los pasos detallados para convertir Word a SVG son los siguientes.

  • Crea un objeto de documento.
  • Cargue un archivo de Word usando el método Document.loadFromFile().
  • Guarde el documento como una lista de matrices de bytes utilizando el método Document.saveToSVG().
  • Recorra los elementos de la lista para obtener una matriz de bytes específica.
  • Escriba la matriz de bytes en un archivo 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);
                }
            }
        }
    }

Convierta Word a PNG con resolución personalizada

Una imagen con mayor resolución generalmente es más clara. Puede personalizar la resolución de la imagen mientras convierte Word a PNG siguiendo los siguientes pasos.

  • Crea un objeto de documento.
  • Cargue un archivo de Word usando el método Document.loadFromFile().
  • Convierta el documento en imágenes BufferedImage con la resolución especificada utilizando el método Document.saveToImages().
  • Recorra la colección de imágenes para obtener la específica y guárdela como un archivo 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);
            }
        }
    }

Java: Convert Word to Images (JPG, PNG and SVG)

Solicitar 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.

Ver también

메이븐으로 설치

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

관련된 링크들

Word 문서를 이미지로 변환해야 하는 데에는 여러 가지 이유가 있습니다. 예를 들어, 많은 장치에서는 특별한 소프트웨어 없이도 이미지를 직접 열고 표시할 수 있으며, 이미지가 전송될 때 콘텐츠를 변조하기가 어렵습니다. 이 기사에서는 다음 방법을 배웁니다 Word를 널리 사용되는 이미지 형식으로 변환 Spire.Doc for Java 사용하여 JPG, PNGSVG와 같은 파일을 만들 수 있습니다.

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>14.2.4</version>
    </dependency>
</dependencies>

Java에서 Word를 JPG로 변환

Spire.Doc for Java 전체 Word 문서를 개별 BufferedImage 이미지로 변환하는 Document.saveToImages() 메서드를 제공합니다. 그런 다음 각 BufferedImage를 BMP, EMF, JPEG, PNG, GIF 또는 WMF 파일로 저장할 수 있습니다. 다음은 이 라이브러리를 사용하여 Word를 JPG로 변환하는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.loadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.saveToImages() 메서드를 사용하여 문서를 BufferedImage 이미지로 변환합니다.
  • 특정 컬렉션을 얻으려면 이미지 컬렉션을 반복하세요.
  • 다른 색상 공간으로 이미지를 다시 작성합니다.
  • 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);
            }
        }
    }

Java에서 Word를 SVG로 변환

Spire.Doc for Java 사용하면 Word 문서를 바이트 배열 목록으로 저장할 수 있습니다. 그런 다음 각 바이트 배열을 SVG 파일로 작성할 수 있습니다. Word를 SVG로 변환하는 자세한 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.loadFromFile() 메서드를 사용하여 Word 파일을 로드합니다.
  • 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로 변환하는 동안 이미지 해상도를 사용자 지정할 수 있습니다.

  • 문서 개체를 만듭니다.
  • Document.loadFromFile() 메서드를 사용하여 Word 파일을 로드합니다.
  • Document.saveToImages() 메서드를 사용하여 문서를 지정된 해상도의 BufferedImage 이미지로 변환합니다.
  • 이미지 컬렉션을 반복하여 특정 컬렉션을 얻고 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);
            }
        }
    }

Java: Convert Word to Images (JPG, PNG and SVG)

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

Installa con Maven

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>spire.doc</artifactId>
    <version>12.2.2</version>
</dependency>
    

Link correlati

Esistono molti motivi per cui potrebbe essere necessario convertire i documenti Word in immagini. Ad esempio, molti dispositivi possono aprire e visualizzare le immagini direttamente senza alcun software speciale e quando le immagini vengono trasmesse il loro contenuto è difficile da manomettere. In questo articolo imparerai come farlo convertire Word nei formati di immagine più diffusi come JPG, PNG e SVG utilizzando Spire.Doc for Java.

Installa Spire.Doc for Java

Innanzitutto, 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>14.2.4</version>
    </dependency>
</dependencies>

Converti Word in JPG in Java

Spire.Doc for Java offre il metodo Document.saveToImages() per convertire un intero documento Word in singole immagini BufferedImage. Quindi, ciascuna BufferedImage può essere salvata come file BMP, EMF, JPEG, PNG, GIF o WMF. Di seguito sono riportati i passaggi per convertire Word in JPG utilizzando questa libreria.

  • Creare un oggetto Documento.
  • Carica un documento Word utilizzando il metodo Document.loadFromFile().
  • Converti il documento in immagini BufferedImage utilizzando il metodo Document.saveToImages().
  • Sfoglia la raccolta di immagini per ottenere quella specifica.
  • Riscrivi l'immagine con uno spazio colore diverso.
  • Scrivi BufferedImage in un file 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);
            }
        }
    }

Converti Word in SVG in Java

Utilizzando Spire.Doc for Java, è possibile salvare un documento Word come elenco di array di byte. Ogni array di byte può quindi essere scritto come file SVG. I passaggi dettagliati per convertire Word in SVG sono i seguenti.

  • Creare un oggetto Documento.
  • Carica un file Word utilizzando il metodo Document.loadFromFile().
  • Salva il documento come elenco di array di byte utilizzando il metodo Document.saveToSVG().
  • Passa in rassegna gli elementi nell'elenco per ottenere un array di byte specifico.
  • Scrivi l'array di byte in un file 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);
                }
            }
        }
    }

Converti Word in PNG con risoluzione personalizzata

Un'immagine con una risoluzione più elevata è generalmente più chiara. È possibile personalizzare la risoluzione dell'immagine durante la conversione di Word in PNG seguendo i seguenti passaggi.

  • Creare un oggetto Documento.
  • Carica un file Word utilizzando il metodo Document.loadFromFile().
  • Converti il documento in immagini BufferedImage con la risoluzione specificata utilizzando il metodo Document.saveToImages().
  • Sfoglia la raccolta di immagini per ottenere quella specifica e salvarla come file 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);
            }
        }
    }

Java: Convert Word to Images (JPG, PNG and SVG)

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.

Guarda anche