Aspose pdf convert word to pdf

Word to PDF

Powered by
aspose.com
and
aspose.cloud

Choose Word files
or drop Word files

Use password

This password will be applied to all documents

If you need to convert several Word to one PDF use Merger

Convert Word to PDF online

Use Word to PDF converter to export Word documents to PDF format online. It is completely free.

Our online service can convert Word documents of any complexity. Word documents may contain tables and lists, headers and footers, formulas and graphics, stylized text, and so on. Our converter will parse the content of a Word file to the smallest detail and recreate the corresponding elements in the target PDF format.

Word to PDF Converter online

Converting from Word to PDF format and vice versa is one of the most requested operations with office documents. Word document formats are great when you want to let other people make changes to the content. In contrast, the PDF format is an excellent choice when we need to protect the document from being modified. We need both of the unique features that Word and PDF formats provide. PDF and Word document formats complement each other in some cases and are therefore closely linked in today’s office work. Quite often we want to convert an editable Word document to an immutable PDF file. This may be a contract or some financial data that should not be modified.

Convert Word file to PDF online

To convert Word to PDF format, simply drag and drop a Word file into the data upload field, specify the conversion options, click the ‘Convert’ button, and get your output PDF file in seconds. The resulting PDF content, structure, and style will be identical to the original Word document.

Free Word to PDF Converter is based on Aspose software products, which are widely used around the world for programmatic processing of Word and PDF files with high speed and professional quality of the result.

Need to convert Word files to PDF programmatically? With Aspose.Words for .NET any developer can convert Word to PDF format with just a few lines of C# code.

Modern document-processing C# API creates PDF from Word with high speed. Test the quality of Word to PDF conversion right in a browser. Powerful C# library allows converting Word files to many popular formats.

Save Word as PDF in C#

The following example demonstrates how to convert Word to PDF in C#.

Follow the easy steps to turn a Word file into PDF format. Read Word file from the local drive, then simply save it as PDF, specifying the required file format by PDF extension. For both Word reading and PDF writing you can use fully qualified filenames. The output PDF content and formatting will be identical to the original Word document.


Input file


Upload a file you want to convert

Run code

Output format

Select the target format from the list

using Aspose.Words;

var doc = new Document("Input.docx");
doc.Save("Output.pdf");

using Aspose.Words;

var doc = new Document("Input.docx");
doc.Save("Output.pdf");

using Aspose.Words;

var doc = new Document("Input.docx");

for (int page = 0; page < doc.PageCount; page++)
{
var extractedPage = doc.ExtractPages(page, 1);
extractedPage.Save($"Output_{page + 1}.pdf");
}

using Aspose.Words;

var doc = new Document();
var builder = new DocumentBuilder(doc);

builder.InsertImage("Input.docx");

doc.Save("Output.pdf");

using Aspose.Words;

var doc = new Document();
var builder = new DocumentBuilder(doc);

var shape = builder.InsertImage("Input.docx");
shape.ImageData.Save("Output.pdf");

How to convert Word to PDF

  1. Install ‘Aspose.Words for .NET’.
  2. Add a library reference (import the library) to your C# project.
  3. Open the source Word file in C#.
  4. Call the ‘Save()’ method, passing an output filename with PDF extension.
  5. Get the result of Word conversion as PDF.

C# library to convert Word to PDF

There are three alternative options to install «Aspose.Words for .NET» onto your system. Please choose one that resembles your needs and follow the step-by-step instructions:

  • Install a NuGet Package. See Documentation
  • Install the library using Package Manager Console within Visual Studio IDE
  • Install the library manually using Windows Installer

System Requirements

Our product is fully cross-platform and supports all major .NET implementations following ‘.NET Standard 2.0’ specification:

  • Microsoft .NET Framework, starting from the earliest 2.0 version, and ending with the latest ‘.NET Framework 4.8’
  • .NET Core, starting from the earliest 2.0, and ending with the latest ‘.NET 6’
  • Mono >= 2.6.7

As far as .NET code doesn’t depend on the underlying hardware or operating system, but only on a Virtual Machine, you are free to develop any kind of software for Windows, macOS, Android, iOS and Linux. Just make sure you have installed the corresponding version of .NET Framework, .NET Core, Windows Azure, Mono or Xamarin.

We recommend using Microsoft Visual Studio, Xamarin, and MonoDevelop integrated development environments to create C#, F#, VB.NET applications.

Fore more details please refer to Product Documentation.

You can convert Word to many other file formats:

I am new to Aspose. All i know is, its a useful library for document creation,conversion etc.
please guide me how can i convert any file(MS office) to pdf file since in my project the document uploaded has to be first converted to pdf then saved in some folder on harddrive.
I have downloaded Aspose.Words and Aspose.Pdf for java.
Any example code or link would be very helpful.
Thanks.

BalusC's user avatar

BalusC

1.1m370 gold badges3597 silver badges3543 bronze badges

asked Nov 28, 2012 at 7:47

Zay hf's user avatar

2

My name is Nayyer and I am developer evangelist at Aspose.

  • Aspose.Words for Java offers the feature to convert word files to PDF. For further details, please check Convert word file to PDF Furthermore, it supports variety of document formats i.e. DOC, DOCX, ODT, RTF, EPUB etc. Please check Supported file formats for more information.
  • Aspose.Cells for Java offers the feature to convert Excel worksheets to PDF. For further details, please visit Convert Excel files to PDf
    please check
  • Aspose.Slides for Java offers the feature to convert PowerPoint presentations to PDF. For further details, please check Convert Presentations to PDf
  • Aspose.Pdf for Java offers the feature to convert Text, Image, HTML, XML files to Pdf format.

answered Nov 28, 2012 at 10:23

codewarior's user avatar

codewariorcodewarior

4312 silver badges9 bronze badges

Join the DZone community and get the full member experience.

Join For Free

What’s new in this release?

Earlier, Aspose.Words for .NET version 6.3 supported glossary documents while loading or saving Office Open XML only. But the newer version 6.4 enables exporting Word documents to PDF compliant to PDF/A-1b and Aspose.Words team is also committed to support PDF/A-1a in the next few months as well.

Example: How to export Word to PDF docs compliant to PDF/A-1b?

Document doc = new Document(@»C:TestRendering.doc»);
PdfOptions options = new PdfOptions();
options.Compliance = PdfCompliance.PdfA1b;
doc.SaveToPdf(0, doc.PageCount, @»C:TestRendering Out.pdf», options);

More about Aspose.Words for .NET

Aspose.Words is a word processing component that enables .NET applications to read, write, modify & convert Word documents without using MS Word. Other features include smart tags, document creation, content and formatting manipulation, mail merge abilities, reporting features, DrawingML and support of EPUB, OOXML, DOCX, DOC, WordML, ODT, HTML, XHTML, MHTML, TXT and PDF formats. It supports printing and rendering Word documents to images. Also use Aspose.Words to build applications with Mono.

PDF
Doc (computing)

Opinions expressed by DZone contributors are their own.

Trending

  • Java Platform Renaissance: 42 Practical Design Patterns

  • I’m Done With Unit and Integration Tests

  • Data Mesh Architecture: A Paradigm Shift in Data Engineering

  • The Secret to High-Availability System for the Cloud

1. Добавьте зависимые библиотеки, необходимые для преобразования вложений на локальном компьютере.

Есть два способа добавить зависимости:

1) Настроить адрес удаленного склада aspose

Добавьте конфигурацию в файл settings.xml:

     <profile>

      <id>jdk-1.6</id>

      <activation>

        <jdk>1.6</jdk>

      </activation>

      <repositories>

        <repository>

        <id>AsposeJavaAPI</id>

        <name>Aspose Java API</name>

        <url>http://repository.aspose.com/repo/</url>

        </repository>

      </repositories>

</profile>

Затем проверьте зависимости, такие как aspose.email, aspose.words.aspose.excel, aspose.pdf с официального сайта, и добавьте их в файл pom. Такие как:

<dependency>

<groupId>com.aspose</groupId>

<artifactId>aspose-email</artifactId>

<version>20.3</version>

<classifier>jdk16</classifier>

</dependency>

2) Загрузите пакет jar в частную библиотеку, затем поместите загруженный пакет jar на локальный склад, а затем импортируйте его в проект локально по идее.

Адрес частной библиотеки:

https://repository.aspose.com/repo/com/aspose/

Импортировать шаги

File-> Project Structure ->Modules



2. Отладить функцию преобразования вложений, реализовать функцию преобразования изображений в PDF, преобразования слов в PDF и синтеза PDF в PDF.

Ниже показан эффект объединения двух изображений в PDF-файл, этапы реализации аналогичны, поэтому сначала посмотрите непосредственно на диаграмму эффекта:



Обратите внимание: при использовании почтальона для проверки слияния двух слов вам необходимо установить Content-Type = multipart / form-data в заголовках, в противном случае будет принято менее 2 файлов. Кроме того, в form-data вам необходимо установить ключ параметра для файла, чтобы выбрать файл для передачи в интерфейс в качестве параметра.



Изображение в функцию pdf:

1) Добавить зависимость:

 <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-imaging</artifactId>
            <version>20.3</version>
            <classifier>jdk16</classifier>
</dependency>

Примечание. Репозиторий aspose необходимо указать в файле настроек.

Инструменты следующие:

package com.example.cn.service;

import com.aspose.imaging.Image;
import com.aspose.imaging.License;
import com.aspose.imaging.imageoptions.PdfOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
@Slf4j
public class ImgService {

    @Autowired
    private LicenseService licenseService;

  
    private void getLicense() {
        License license = new License();
        try {
            license.setLicense(licenseService.getLicense());
        } catch (Exception e) {
                         log.error ("Ошибка аутентификации: [{}]", e);
        }
    }

 
    public void imgToPdf(InputStream file, String path) {
        getLicense();
        Image image = Image.load(file);
        image.save(path, new PdfOptions());

    }

    

}

controller:

   @GetMapping(value = "/toPdfAndMerge")
    public ResponseEntity<String> fileUpload(@RequestParam(name = "file1", required = false)
                                                     MultipartFile file1,
                                             @RequestParam(name = "file2", required = false)
                                                     MultipartFile file2) throws Exception {

        List<FileCO> fileCOs = new ArrayList<>();
        if (file1 != null) {
            FileCO fileCO = new FileCO();
            fileCO.setFileContent(file1.getBytes());
            fileCO.setFileName(file1.getOriginalFilename());
            fileCOs.add(fileCO);
        }
        if (file2 != null) {
            FileCO fileCO2 = new FileCO();
            fileCO2.setFileContent(file2.getBytes());
            fileCO2.setFileName(file2.getOriginalFilename());
            fileCOs.add(fileCO2);
        }
        return ResponseEntity.ok(pdfMergeService.testService(fileCOs));
    }

service:

   public String transformation(FileCO fileCO, String type) throws Exception {
        String pdf = "pdf";
        String txt = "txt";
        List<String> xls = Arrays.asList("xls", "xlt", "xml");
        List<String> doc = Arrays.asList("doc", "rtf", "dot");
        List<String> ppt = Arrays.asList("pps", "pot", "ppt");
        List<String> img = Arrays.asList("jpg", "png", "tif", "bmp");
        List<String> eml = Arrays.asList("msg", "eml", "mht", "pst", "ost");
        InputStream file = new ByteArrayInputStream(fileCO.getFileContent());
        String fileName = fileCO.getFileName();
        // Берем суффикс имени
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                 // Принимаем только три цифры
        suffix = suffix.substring(0, 3).toLowerCase();
        String uuid = UUID.randomUUID().toString();

        String lastPath = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now()) + "/";
        File dateFile = new File(path + lastPath);
        if (!dateFile.exists()) {
                         // Создание каталога дат
            dateFile.mkdirs();
        }
                 // Картинки только сжимаются
        if (img.contains(suffix)) {
            lastPath = lastPath + uuid + ".jpg";
        } else if (xls.contains(suffix)) {
            lastPath = lastPath + uuid + ".html";
        } else {
            if (CommonCodeUtils.TO_PDF.equals(type)) {
             lastPath = lastPath + uuid + ".pdf";
            }
            if (CommonCodeUtils.TO_HTML.equals(type)) {
                lastPath = lastPath + uuid + ".html";
            }
        }


        String fullPath = path + lastPath;

        if (pdf.equals(suffix)) {
            if (CommonCodeUtils.TO_HTML.equals(type)) {
                pdfService.pdfToHtml(file, fullPath);
            }
            if (CommonCodeUtils.TO_PDF.equals(type)) {
                pdfService.pdfToPdf(file, fullPath);
            }
        } else if (xls.contains(suffix)) {
                         // excel сжимается только в html
            // if (CommonCodeUtils.TO_HTML.equals(type)) {
            excelService.excelToHtml(file, fullPath);
            // }
            // if (CommonCodeUtils.TO_PDF.equals(type)) {
            //    excelService.excelToPdf(file, fullPath);
            // }
        } else if (doc.contains(suffix)) {
            if (CommonCodeUtils.TO_HTML.equals(type)) {
                wordService.wordToHtml(file, fullPath);
            }
            if (CommonCodeUtils.TO_PDF.equals(type)) {
                wordService.wordToPdf(file, fullPath);
            }
        } else if (ppt.contains(suffix)) {
            if (CommonCodeUtils.TO_HTML.equals(type)) {
                pptService.pptToHtml(file, fullPath);
            }
            if (CommonCodeUtils.TO_PDF.equals(type)) {
                pptService.pptToPdf(file, fullPath);
            }
        } else if (img.contains(suffix)) {
                         // Теперь картинки сжимаются и конвертируются в jpg
           // imgService.imgToPdf(file,fullPath);
           // ImageHelper.scaleImage(file, fullPath, imageScale, "jpg");
            if (CommonCodeUtils.TO_PDF.equals(type)){
                imgService.imgToPdf(file,fullPath);
            }

        } else if (eml.contains(suffix)) {

//            byte[] bytes=fileCO.getFileContent();
//            getFileByBytes(bytes,fullPath);
            if (CommonCodeUtils.TO_PDF.equals(type)) {
             // mailService.emlToHtml(file, fullPath);
                mailService.emlToPdf(file,fullPath);
            }
        } else if (txt.contains(suffix)) {
            txtService.txtToHtml(fileCO.getFileContent(), fullPath, fileName);
        } else {
            return null;
        }

        return lastPath;
    }

Объедините файлы pdf:

 public void mergePdfFiles(List<String> files, String newFile) throws IOException, DocumentException {
        PdfReader pdfReader = new PdfReader(files.get(0));
        Document document = new Document(pdfReader.getPageSize(1));
        pdfReader.close();
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFile));
        document.open();
        for (int i = 0; i < files.size(); i++) {
            PdfReader reader = new PdfReader(files.get(i));
            int n = reader.getNumberOfPages();
            for (int j = 1; j <= n; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }
            reader.close();
        }
        copy.close();
        document.close();
                 log.debug («Удаление одного файла»);
        files.forEach(e -> {
            File dateFile = new File(e);
            if (dateFile.exists()) {
                dateFile.delete();
            }
        });
    }

3. Реализуйте функцию локального преобразования электронных писем в PDF.

Идея реализации: сначала преобразовать тип электронной почты в html, затем в PDF, электронная почта -> html-> pdf

Чтобы передать параметры, content-Type = application / x-emf

Основной код выглядит следующим образом:



Преобразование электронной почты в HTML:

 public void emlToHtml(InputStream file, String path) {
        MailMessage messageEML = MailMessage.load(file);
        messageEML.save(path, SaveOptions.getDefaultHtml());
    }

Конвертировать html в pdf:

 public void emlToPdf(InputStream file,String path) throws Exception {

                 // ByteArrayInputStream преобразуется во входной поток
//        Presentation doc = new Presentation(file);
//        doc.save(path, SaveFormat.Pdf);
        emlToHtml(file,path);
                 // Конвертировать в PDF
        getLicense();
        Document doc = new Document(path);
        doc.save(path, SaveFormat.PDF);

//        getLicense();
//        Workbook workbook = new Workbook(file);
//        workbook.save(path, com.aspose.cells.SaveFormat.PDF);
    }

Перед конвертацией в pdf необходимо получить лицензию, то есть сертификат:

Проверьте, если лицензия не добавлена, между двумя PDF-файлами, синтезированными API, будет водяной знак aspose. следующим образом:

 

Появилась огромная яма! Проблема с водяными знаками очень велика, потому что она не решена, этот Peugeot слишком бросается в глаза, покупатель определенно будет недоволен, а затем попытается импортировать в соответствии с подсказкой.лицензия aspose.words, После перенаправления пакета водяной знак устранен!

  

Класс лицензии должен быть в пакете aspose.words:

Таким же образом: сначала получите лицензию, а затем конвертируйте eml в html файл в PDF.

Два письма без водяных знаков объединяются в один PDF-файл!

Понравилась статья? Поделить с друзьями:
  • Aspose excel to pdf
  • Aspects of word stress
  • Asking too many questions word
  • Aspects of word meaning lexicology
  • Asking sentence with the word but