Android加载pdf
依赖
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.github.barteksc:android-pdf-viewer:3.2.0-beta.1'
在project.build中添加该源
maven { url "https://repository.liferay.com/nexus/content/repositories/public/" }
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Activity
import android.os.Bundle;
import android.os.Environment;
import androidx.appcompat.app.AppCompatActivity;
import com.github.barteksc.pdfviewer.PDFView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
private PDFView pdfView;
private static final String PDF_URL = "https://www.example.com/sample.pdf"; // 替换为你的 PDF URL
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfView = findViewById(R.id.pdfView);
downloadAndDisplayPdf(PDF_URL);
}
private void downloadAndDisplayPdf(String url) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
File pdfFile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "downloaded.pdf");
try (InputStream inputStream = response.body().byteStream();
FileOutputStream outputStream = new FileOutputStream(pdfFile)) {
byte[] buffer = new byte[2048];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
// 在主线程中加载 PDF
runOnUiThread(() -> pdfView.fromFile(pdfFile).load());
}
}
}
});
}
}
PDF不支持在线预览,因此要先下载后加载
• 下载 PDF 文件:使用 OkHttp 请求 PDF 的在线地址,并将其保存到设备的下载目录中。
• 加载 PDF 文件:下载完成后,通过 pdfView.fromFile(pdfFile).load() 在 PDFView 中显示 PDF 文件。