Вот что я пробовал:
- Добавление Изображения с тегами. Я могу добавлять изображения на определенные страницы PDF-файла и присваивать каждому изображению тег для идентификации.
Код: Выделить всё
private void appendImageToPdf(int id, int pageNumber, String tag) throws IOException {
InputStream input = getContentResolver().openInputStream(pdfUri);
PDDocument document = PDDocument.load(input);
PDPage page = document.getPage(pageNumber);
PDRectangle pageSize = page.getMediaBox();
pageWidth = pageSize.getWidth();
pageHeight = pageSize.getHeight();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), id);
PDImageXObject pdImage = LosslessFactory.createFromImage(document, bitmap);
float imageWidth = 70;
float imageHeight = 70;
float x = (pageWidth - imageWidth) / 2;
float y = (pageHeight - imageHeight) / 2;
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
contentStream.drawImage(pdImage, x, y, imageWidth, imageHeight);
imagePositions.add(new ImageDetails((int) x, (int) y, (int) imageWidth, (int) imageHeight, pageNumber, tag));
COSDictionary imageDictionary = pdImage.getCOSObject();
imageDictionary.setString(COSName.getPDFName("Tag"), tag);
contentStream.close();
File file = new File(getExternalFilesDir(null), "updated.pdf");
document.save(file);
document.close();
input.close();
pdfUri = Uri.fromFile(file);
displayPdf(pdfUri, currentPage);
}
- Удаление изображений по тегу. Вот метод, который я использую для удаления изображений из PDF-файла на основе их тега. Несмотря на использование этого метода, изображения остаются в документе.
Код: Выделить всё
private void removeImageFromPdf(String tag) throws IOException {
InputStream input = getContentResolver().openInputStream(pdfUri);
PDDocument document = PDDocument.load(input);
for (PDPage page : document.getPages()) {
COSDictionary pageDict = page.getCOSObject();
COSBase contents = pageDict.getItem(COSName.CONTENTS);
if (contents instanceof COSArray) {
COSArray contentsArray = (COSArray) contents;
removeTagFromContents(contentsArray, tag);
} else if (contents instanceof COSObject) {
COSBase actualBase = ((COSObject) contents).getObject();
if (actualBase instanceof COSArray) {
removeTagFromContents((COSArray) actualBase, tag);
} else if (actualBase instanceof COSStream) {
removeTagFromStream((COSStream) actualBase, tag);
}
} else if (contents instanceof COSStream) {
removeTagFromStream((COSStream) contents, tag);
}
}
File file = new File(getExternalFilesDir(null), "updated.pdf");
document.save(file);
document.close();
input.close();
pdfUri = Uri.fromFile(file);
displayPdf(pdfUri, currentPage);
}
private void removeTagFromContents(COSArray contents, String tag) throws IOException {
for (int i = 0; i < contents.size(); i++) {
COSBase base = contents.getObject(i);
if (base instanceof COSDictionary) {
COSDictionary dict = (COSDictionary) base;
COSString cosTag = (COSString) dict.getItem(COSName.getPDFName("Tag"));
if (cosTag != null && tag.equals(cosTag.getString())) {
contents.remove(i);
i--; // Decrement the index to account for the removal
}
} else if (base instanceof COSStream) {
removeTagFromStream((COSStream) base, tag);
}
}
}
private void removeTagFromStream(COSStream stream, String tag) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(stream.getUnfilteredStream().readAllBytes());
String content = byteArrayOutputStream.toString();
byteArrayOutputStream.close();
// Implement logic to remove tagged content from the stream's content string
// This is a complex task and requires parsing the PDF content stream
// Example: Removing tagged content (simplified, real implementation needed)
content = content.replaceAll("/Tag \\(" + tag + "\\).*?EI", "");
stream.removeItem(COSName.LENGTH);
stream.setItem(COSName.LENGTH, new COSString(String.valueOf(content.length())));
stream.setData(content.getBytes());
}
- Как правильно удалить отмеченные изображения из PDF-файла?
- Есть ли лучший подход к маркировке и идентификации изображений для удаления в PDFBox?
Подробнее здесь: https://stackoverflow.com/questions/786 ... droid-java