将 Android 视图调整为标准 pdf 大小时出现问题

问题描述 投票:0回答:1

我正在尝试从动态构建的 android 视图生成 pdf 文档。无论我做什么,android 视图都不会重新调整大小以在 pdf 上正确绘制。另外,我猜 pdf 的大小是以点为单位的,而视图当前是以像素为单位设置的。


    private var heightInPixels = 1100
    private var widthInPixels = 850
    private val heightLetterPaperInPoints = 792
    private val widthLetterPaperInPoints  = 612

    private fun createPdf() {
        try {
            val data = viewModel.getData(info, requireContext())
            val view2: View =
                LayoutInflater.from(requireContext()).inflate(R.layout.pdf_layout, null)
            val titleTextView = view2.findViewById<TextView>(R.id.title)
            val selectionsContainer = view2.findViewById<LinearLayout>(R.id.selections_container)
            for (item in data) {
                val selectionViewBinding = ItemPdfSelectionBinding.inflate(layoutInflater)
                selectionViewBinding.itemTitle.text = item.title
                selectionViewBinding.selectionName.text = item.selectionName
                selectionsContainer.addView(selectionViewBinding.root)
            }
            val pageInfo =
                PageInfo.Builder(widthLetterPaperInPoints, heightLetterPaperInPoints, 1).create()
            val page = pdfDocument.startPage(pageInfo)
            view2.measure(
                View.MeasureSpec.makeMeasureSpec(
                    (widthInPixels).toInt(),
                    View.MeasureSpec.UNSPECIFIED
                ),
                View.MeasureSpec.makeMeasureSpec(
                    (heightInPixels).toInt(),
                    View.MeasureSpec.UNSPECIFIED
                )
            )
            view2.layout(0, 0, widthInPixels, heightInPixels)
            view2.draw(page.canvas)
            pdfDocument.finishPage(page)
        } catch (t: Throwable) {

        }
    }

我也尝试过:

view2.scaleX = .72 view2.scaleY = .72

在测量视图之前,这也没有任何作用。

android kotlin android-layout pdf
1个回答
0
投票

问题在于您使用了

View.MeasureSpec.UNSPECIFIED
来测量视图。

文档这意味着

父母没有对孩子施加任何约束。它可以是任何它想要的尺寸。

这意味着您对视图大小没有任何限制,因此它会根据需要将其绘制得尽可能大,因此您指定的宽度和高度(以像素为单位)将被忽略。

您应该使用

View.MeasureSpec.AT_MOST
告诉视图它不能超过 PDF 页面的宽度(以每英寸 72 个 postscript 点(像素)测量)。然后它将使用您提供的像素大小作为最大值

您也可以

View.MeasureSpec.EXACTLY
,但是诸如将视图居中之类的行为会有所不同。

© www.soinside.com 2019 - 2024. All rights reserved.