Просмотрщик PDF-файлов (с масштабированием и производительностью) в MAUI/Blazor сAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Просмотрщик PDF-файлов (с масштабированием и производительностью) в MAUI/Blazor с

Сообщение Anonymous »

Я пытаюсь показать простой PDF-файл в нашем веб-приложении MAUI на устройстве Android. Кажется, это сложнее, чем необходимо. Версия с холстом работает, но производительность ужасная.
Интернет и искусственный интеллект предлагают PDF.js в качестве решения и использование WebView в качестве основы. Однако при запуске он всегда отображается в виде белого пустого изображения. Кроме того, Visual Studio для Mac также помечает WebView (или BlazorWebView) как недоступный, что заставляет меня думать, что она просто игнорирует этот тег.
Предупреждение: «Обнаружен элемент разметки с неожиданным именем BlazorWebViewHostPage». . Если это
компонент, добавьте директиву @using для его пространства имен"

Код: Выделить всё

@page "/pdfviewer"
@using Microsoft.AspNetCore.Components.WebView.Maui
@inject TemporaryFileService TemporaryFileService
@inject NavigationManager Navigation
@using ProjectNameMobileMaui.Services





PDF Viewer



Loading...







@code {
[Parameter]
public string FileName { get; set; }
private string FilePath;

protected override void OnParametersSet()
{
Console.WriteLine("OnParametersSet called");
var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
FileName = query["fileName"];
Console.WriteLine($"FileName parameter: {FileName}");

if (!string.IsNullOrEmpty(FileName))
{
FilePath = Path.Combine(TemporaryFileService.GetTempDirectory(), FileName);
Console.WriteLine($"Calculated FilePath: {FilePath}");
}
else
{
Console.WriteLine("FileName parameter is null or empty");
}
}
}
Есть сведения?
Части моего файла csproj:

Код: Выделить всё



net8.0-android;net8.0-ios;net8.0-maccatalyst
$(TargetFrameworks);net8.0-windows10.0.19041.0

Exe
true
true
true
enable
false
enable


1.0
3

14.2
14.0
24.0
10.0.17763.0
10.0.17763.0
6.5



d8
apk












И pdfViewer.html:

Код: Выделить всё



PDF Viewer

body {
margin: 0;
padding: 0;
overflow: hidden;
}

#pdfContainer {
width: 100vw;
height: 100vh;
touch-action: none;
}

canvas {
touch-action: none;
}




PDF Viewer Loaded
console.log("PDF Viewer script started");
document.getElementById('pdfContainer').innerHTML += "
Script Started";

const urlParams = new URLSearchParams(window.location.search);
const filePath = urlParams.get('filePath');
console.log(`filePath from URL: ${filePath}`);
document.getElementById('pdfContainer').innerHTML += `
filePath from URL: ${filePath}`;

if (!filePath) {
console.error('No file path found');
document.getElementById('pdfContainer').innerHTML += "
No file path found";
} else {
fetch(filePath)
.then(response => {
console.log("Fetch response received, status:", response.status);
document.getElementById('pdfContainer').innerHTML += `
Fetch response status: ${response.status}`;
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.arrayBuffer();
})
.then(pdfData => {
console.log("PDF data loaded");
document.getElementById('pdfContainer').innerHTML += "
PDF data loaded";
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js';

return pdfjsLib.getDocument({ data: pdfData }).promise;
})
.then(pdf => {
console.log("PDF document loaded");
document.getElementById('pdfContainer').innerHTML += "
PDF document loaded";
return pdf.getPage(1);
})
.then(page => {
console.log("PDF page loaded");
document.getElementById('pdfContainer').innerHTML += "
PDF page loaded";
const scale = 1.5;
const viewport = page.getViewport({ scale: scale });

const container = document.getElementById('pdfContainer');
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
container.appendChild(canvas);

const renderContext = {
canvasContext: context,
viewport: viewport
};
return page.render(renderContext).promise;
})
.then(() => {
console.log("PDF page rendered");
document.getElementById('pdfContainer').innerHTML += "
PDF page rendered";
})
.catch(error =>  {
console.error('Error loading PDF:', error);
document.getElementById('pdfContainer').innerHTML += `
Error loading PDF: ${error.message}`;
});
}



Обновить
Попробовал это руководство но безуспешно:< /p>
Сейчас я получаю следующие ошибки:

Код: Выделить всё

[chromium] [INFO:CONSOLE(381)] "Warning: Setting up fake worker.", source: file:///android_asset/pdfjs/build/pdf.js (381)
[chromium] [INFO:CONSOLE(40018)] "Uncaught TypeError: pattern.at is not a function", source: file:///android_asset/pdfjs/build/pdf.worker.js (40018)
[chromium] [INFO:CONSOLE(40018)] "Uncaught TypeError: pattern.at is not a function", source: file:///android_asset/pdfjs/build/pdf.worker.js (40018)
[chromium] [INFO:CONSOLE(910)] "An error occurred while loading the PDF.
[chromium]
[chromium] PDF.js v3.11.174 (build: ce8716743)
[chromium] Message: Setting up fake worker failed: "Cannot read property 'WorkerMessageHandler' of undefined".", source: file:///android_asset/pdfjs/web/viewer.js (910)
[chromium] [INFO:CONSOLE(1927)] "Uncaught (in promise) Error: Setting up fake worker failed: "Cannot read property 'WorkerMessageHandler' of undefined".", source: file:///android_asset/pdfjs/build/pdf.js (1927)
Я пробовал как новейшую версию (4.3.136), так и последнюю версию 3.x. Я также попробовал устаревшую версию версии 3.x.

Подробнее здесь: https://stackoverflow.com/questions/786 ... lazor-with
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»