Я пробовал написать простой метод, который отображает представление из макета Android и преобразует его в PDF с использованием класса PdfDocument. По какой-то причине полученный PDF всегда равен 0 байтам.PDF, созданный в android через PdfDocument, равен 0 байтам
Вот мой код для создания PDF. Позже в приложение, которое я буду прикрепление его к электронной почте программно, так что я в настоящее время получаю его в качестве объекта File:
public static File generate(View salesFragmentTableLayout, Context context) throws KingdomSpasException {
PdfDocument document = new PdfDocument();
PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();
Page page = document.startPage(pageInfo);
salesFragmentTableLayout.draw(page.getCanvas());
document.finishPage(page);
File result = null;
try {
result = File.createTempFile("Kingdom Spas Agreement", ".pdf", context.getCacheDir());
document.writeTo(new BufferedOutputStream(new FileOutputStream(result)));
} catch (FileNotFoundException e) {
throw new KingdomSpasException("Failed to find relevent file", e);
} catch (IOException e) {
throw new KingdomSpasException("IO Problem occured while creatin the PDF", e);
}
document.close();
return result;
}
Это в настоящее время называется от моего модульного тестирования - у меня нет точки где я интегрирую его в фактическое приложение. Только в случае, если проблема вызвана мой тестовый код, я добавляю его здесь, а также:
public void testGetPDFFile() {
LayoutInflater inflater = LayoutInflater.from(getContext());
View salesAgreementLayout = inflater.inflate(R.layout.sales_agreement_layout, null);
View salesAgreementTableLayout = salesAgreementLayout.findViewById(R.id.salesAgreementTableLayout);
EditText initials = (EditText) salesAgreementTableLayout.findViewById(R.id.salesExecInitials);
initials.setText("Test Initials");
File pdfFile = null;
try {
pdfFile = KingdomSpasFormsPDFGenerator.generate(salesAgreementTableLayout, getContext());
} catch (KingdomSpasException e) {
Log.e(TAG, "Failed to create the PDF file.",e);
}
assertNotNull(pdfFile);
assertTrue(pdfFile.length() > 0);
}
Второе утверждение в настоящее время не удается.
Для завершения, здесь полный макет, используемый в деятельности:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:kingdomspas="http://www.kingdomspas.com/android/custom"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/salesAgreementTableLayout">
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/companyLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:contentDescription="@string/logo_description"
android:src="@drawable/company_logo" />
<ImageView
android:id="@+id/companyAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:contentDescription="@string/address_description"
android:src="@drawable/company_address" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="@+id/salesExecInitials"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/round"
android:inputType="text"
android:maxLines="1"
android:paddingLeft="130dp"
android:singleLine="true" >
<requestFocus />
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="10dp"
android:text="@string/sales_exec_initials" />
</FrameLayout>
</TableRow>
</TableLayout>
<View
android:paddingTop="50dp"
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_weight="1"
android:background="@android:color/darker_gray" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/submit"
android:text="@string/submit_form"
android:padding="10dp"/>
</LinearLayout>
</ScrollView>
Я полагаю, это просто что-то глупо, что я пропускаю или сделали неправильно - но я не могу видеть это сам. Есть идеи?
Вы в конечном итоге решили это? У меня такая же проблема. – user1163234
Для меня это было вызвано запуском кода из модульного теста. Он работал, когда я запускал его в самом приложении. –