问题
I want to add an electronic signature to a pdf. i am using signature pad library for capturing signature and sticker view for moving, scaling and rotating image StickerView. I am rendering the PDF in android using PDFView library to render PDF.
i am using PDFbox by tomroush to manipulate pdf in android. i want to add image of signature to the pdf. but there is problem in mapping android view coordinates to pdf box coordinates. i am attaching code for what i have tried
//loading pdf
pdfView.fromUri(pdf_location).enableSwipe(true).defaultPage(0).onPageError(new OnPageErrorListener() {
@Override
public void onPageError(int page, Throwable t) {
t.printStackTrace();
}
}).load();
Loading PDF in PDDOcumnet code
//loading document in PDF box PDDocument object
PDDocument document = PDDocument.load(getContentResolver().openInputStream(pdf_location));
PDPage currentPage = document.getPage(pdfView.getCurrentPage());
PDImageXObject image = PDImageXObject.createFromFile(fName, document);
PDPageContentStream contentStream = new PDPageContentStream(document, currentPage, true, false);
Calculating Width and height of image (scaling image)
float width = iv_sticker.getImageDrawable().getIntrinsicWidth() * (( 72.0f / getResources().getDisplayMetrics().densityDpi));
float height = iv_sticker.getImageDrawable().getIntrinsicHeight() * ((72.0f / getResources().getDisplayMetrics().densityDpi));
Drawing image on pdf
contentStream.drawImage(image,iv_sticker.getX() * (currentPage.getMediaBox().getWidth() / pdfView.getOptimalPageWidth()), (currentPage.getMediaBox().getWidth() - (iv_sticker.getY() * (currentPage.getMediaBox().getHeight() / pdfView.getOptimalPageHeight()))) - (height), width, height);
In the last code snippet i am finding the ratio of pdf view width and PDPage Width and then multiplying it to the image X coordinate to find corresponding X coordinate on pdf. And Doing same for y coordinate .The only difference with Y coordinate mapping is that i am subtracting the y coordinate from PDF Page Height because PDF coordinate starts from Bottom Left and then subtracting the image height so that image does not go outside of page. But the output is not perfect i am attaching screenshots.
Image Of My App
Image Of PDF after running the above code after adding signature
来源:https://stackoverflow.com/questions/63823704/how-to-convert-android-imageview-coordinate-to-pdfview-coordinate-for-adding-ele