Word处理控件Aspose.Words功能演示:使用 Android 库将 Word 文档转换为 PDF

Aspose.Words 是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。此外,

Aspose API支持流行文件格式处理,并允许将各类文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。

Word到 PDF是广泛应用的文档转换之一,这就是MS Word提供将 Word 文档另存为 PDF 的内置功能的原因。由于 PDF 是共享文档或在线保存文档的首选格式,因此在各种情况下都需要将 Word 转换为 PDF。另一方面,基于 Android 的智能手机通过应用程序在手机中添加了大量功能,从而让人们的生活更加轻松。密切关注这些趋势,在本文中,我将向您展示如何在 Android 应用程序中将 Word 文档转换为 PDF。为了进行演示,我们将通过几个步骤为 Android构建一个简单的Word 到 PDF 转换器应用程序,该应用程序具有以下功能。

一、适用于 Android 的 Word 到 PDF 转换器库

为了将 MS Word 文档转换为 PDF 格式,我们将通过 Java 使用 Aspose.Words for Android,它允许您使用几行代码将 DOC/DOCX 文档无缝转换为 PDF 文件。您可以下载API 或使用Maven 配置安装它。

二、在 Android 中将 Word 转换为 PDF 的步骤

以下是通过 Java 使用 Aspose.Words for Android在 Android 中创建一个简单的 Word 到 PDF 转换器应用程序的步骤:

  • 在 Android Studio(或 Eclipse)中创建一个新项目并选择“Empty Activity”模板。

  • 配置您的项目。

  • 打开build.gradle文件。

  • 在build.gradle中添加以下存储库部分。
repositories {
    mavenCentral()
    maven { url "https://repository.aspose.com/repo/" }
}
  • 在build.gradle的依赖项部分添加以下条目。
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.android.support:multidex:2.0.0'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
compile (group: 'com.aspose', name: 'aspose-words', version: '20.6', classifier: 'android.via.java')
  • 通过在build.gradle的defaultConfig部分下添加以下条目来启用 multidex 。
// enable multiDex
multiDexEnabled true
  • 完整的build.gradle文件如下所示:
apply plugin: 'com.android.application'

android {
compileSdkVersion 30
buildToolsVersion "30.0.1"

defaultConfig {
applicationId "com.example.wordtopdf"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
// enable multiDex
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

repositories {
mavenCentral()
maven { url "https://repository.aspose.com/repo/" }
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.android.support:multidex:2.0.0'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
compile (group: 'com.aspose', name: 'aspose-words', version: '20.6', classifier: 'android.via.java')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
  • 打开activity_main.xml文件。

  • 为主要活动的布局粘贴以下脚本。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="-26dp"
tools:layout_editor_absoluteY="-16dp" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#D3FFFFFF"
android:textColor="#A3A2A2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteY="39dp" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="408dp"
android:layout_gravity="bottom|right"
android:layout_marginEnd="36dp"
android:layout_marginRight="36dp"
android:layout_marginBottom="140dp"
app:backgroundTint="#00BCD4"
app:layout_anchorGravity="bottom|right|end"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pdfView"
app:srcCompat="@android:drawable/stat_sys_upload"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • 打开MainActivity.java文件。

  • 将以下 Java 代码粘贴到MainActivity.java中。
package com.example.wordtopdf;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.github.barteksc.pdfviewer.PDFView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.FROYO)
public class MainActivity extends AppCompatActivity {

private static final int PICK_PDF_FILE = 2;
private final String storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator;
private final String outputPDF = storageDir + "Converted_PDF.pdf";
private TextView textView = null;
private Uri document = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// apply the license if you have the Aspose.Words license...
applyLicense();
// get treeview and set its text
textView = (TextView) findViewById(R.id.textView);
textView.setText("Select a Word DOCX file...");
// define click listener of floating button
FloatingActionButton myFab = (FloatingActionButton) findViewById(R.id.fab);
myFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
// open Word file from file picker and convert to PDF
openaAndConvertFile(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

private void openaAndConvertFile(Uri pickerInitialUri) {
// create a new intent to open document
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// mime types for MS Word documents
String[] mimetypes = {"application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/msword"};
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
// start activiy
startActivityForResult(intent, PICK_PDF_FILE);
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);

if (resultCode == Activity.RESULT_OK) {
if (intent != null) {
document = intent.getData();
// open the selected document into an Input stream
try (InputStream inputStream =
getContentResolver().openInputStream(document);) {
Document doc = new Document(inputStream);
// save DOCX as PDF
doc.save(outputPDF);
// show PDF file location in toast as well as treeview (optional)
Toast.makeText(MainActivity.this, "File saved in: " + outputPDF, Toast.LENGTH_LONG).show();
textView.setText("PDF saved at: " + outputPDF);
// view converted PDF
viewPDFFile();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found: " + e.getMessage(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}

public void viewPDFFile() {
// load PDF into the PDFView
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
pdfView.fromFile(new File(outputPDF)).load();
}
public void applyLicense()
{
// set license
License lic= new License();
InputStream inputStream = getResources().openRawResource(R.raw.license);
try {
lic.setLicense(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
  • 构建应用程序并在您的 Android 智能手机或虚拟设备中运行它。
  • 通过转到Settings->Apps->Permissions->Permission manager->Storage允许此应用访问存储。

以上便是在使用 Android 库将 Word 文档转换为 PDF ,要是您还有其他关于产品方面的问题,欢迎咨询我们,或者加入我们官方技术交流群。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值