How to view DJVU file in UIWebview - ios

I am having iOS application in which I want to view data from .djvu file. Is there any way to read .djvu file in Swift or inside UIWebview.
I have also tried following solutions to view djvu file in uiwebview but that doesn't help.
1. Directly open djvu file in uiwebview
let urlPage : URL! = URL(string: "http://192.168.13.5:13/myData/5451890-OP.djvu")
webView.loadRequest(URLRequest(url: urlPage))
2. Secondly i have tried to convert djvu file to pdf and the showing that converted pdf file into view.
Reference link: https://github.com/MadhuriMane/ios-djvu-reader
But that gives mirror image with low quality.
3. I have tried to preview file with the help of UIDocumentInteractionController() and it's delegate method but didn't work.
Please suggest any possible ways to do so.

Keeping in mind that .djvu files are less popular then similar formats like EPUB, MOBI, PDF and other eBook file formats, I would have following approach to workaround the problem.
1) Create a Web Service to convert djvu files to pdf
ex.: http://example.com/djvuToPdf/djvuFile/outputFile
2) Read the PDF file in UIWebView
To create a Web Service I would assume that you have access to any Linux distributed Server, in my case Ubuntu 16.04.
Step one: Install djvulibre
sudo apt-get install djvulibre-bin ghostscript
Step two: test run $ djvups inputFile.djvu | ps2pdf - outputFile.pdf.
You may also use the ddjvu command. However, files converted with ddjvu command are 10x larger than djvups command. You would want to consider to use --help the explore the settings like mode, quality and so on.
Step three: Creating a Web Service (to keep things simple, I use PHP, use anything at your convenience [Python golang])
<?php
$inputFile = $_GET['input_file'];
$outputFile = $_GET['output_file'];
// use shell exec to execute the command
// keep in mind that the conversion takes quite a long time
shell_exec(sprintf("djvups %s | ps2pdf - %s", $inputFile, $outputFile));
$name = $outputFile;
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;
?>
Final Step: load PDF in App
As Apple advise, consider using WKWebView in place of UIWebView.
if let pdfURL = Bundle.main.url(forResource: "pdfFile", withExtension: "pdf", subdirectory: nil, localization: nil) {
do {
let data = try Data(contentsOf: pdfURL)
let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
view.addSubview(webView)
}
catch {
// catch errors here
}
}

Related

Load Server URL dicom files inside Imebra in iOS?

I am using https://imebra.com/ in my application, when I load a local files it reading the DICOM file and I am able to see the Image. when, I am sending Cloud url path to imebra It is showing an error and below I shared sample code.I want to send a single or multiple url to Imebra. I don't know how to proceed.
let filePath = Bundle.main.path(forResource: fileName, ofType: "dcm") // i want to send url(https://raw.githubusercontent.com/ivmartel/dwv/master/tests/data/bbmri-53323851.dcm) here
let dataSet = try ImebraCodecFactory.load(fromFile: filepath)
_ = try dataSet.getString(ImebraTagId(group: 0x10, tag: 0x10), elementNumber: 0, defaultValue: "")
_ = try dataSet.getString(ImebraTagId(group: 0x10, tag: 0x10), elementNumber: 1, defaultValue: "")
thanks in advance.
Imebra can load local DICOM files or from remote PACS (using the DIMSE protocol).
Imebra cannot load an image directly from an URL because it uses a posix call to open the local file.
To open a file from an URL you should first load the remote file. See this answer Simple Swift file download with URL to see how to load a file to a local temporary file.
Alternatively, you could load the file to a NSData object and pass its content to an Imebra Memory object, then pass to ImebraCodecFactory a StreamReader using a MemoryStreamInput.
Disclaimer: I'm the author of Imebra

Wkwebview cannot display images in html having path of library directory

I have studied similar questions but couldnot find solution.
I am using WkWebView. It renders a html from library directory so i did loadfileurl.
It has option of displaying an image, we select the image from gallery/take camera , then from image data wecreate a file in library directory and sendthe path to web .
I tried both path var/... and also appended file://
both cases image is not displaying.
Please help.
Any suggestions appreciated.
An alternative would be to encode the images as base64 strings and insert them into the HTML before rendering. You could either save the images as images or the base64 string, depending on whether you need to use them in another context.
// Get the base64 representation of the image
let image = UIImage(named: icon) // This could also be loaded from the file system
let data = image!.pngData()
let b64String = String(data: data!.base64EncodedData(), encoding: String.Encoding.utf8)!
let finalString = "data:image/png;base64," + b64String
// Insert into HTML string before rendering in webview
let myHTML = baseHTML.replacingOccurrences(of: "#PLACEHOLDER#", with: finalString)
You will need to have #PLACEHOLDER# in your HTML file at the point where you would have the path to the image.

How download files on app mobile with PHPSpreadsheet?

for my project I'm using PHPSpreadsheet for exporting data in Excel and PDF format.
If from the website, when I press on the respective download buttons, I can easily download the .xlsx and .pdf files, I have problems with the app (iOs Swift language). In fact, when I try to download the files, I receive the following messages:
for Excel files: "the file may be damaged"
for PDF files (I open it with Chrome): "Chrome does not support this link file: ///var/mobile/Containers/Data/Application/.../Documents/name_file.pdf"
Here are the fragments of the PHP code that deal with the download:
PDF:
$ output. = '... html code';
$ mpdf = new \ Mpdf \ Mpdf ();
$ mpdf-> Bookmark ('Start of the document');
$ Mpdf-> WriteHTML ($ output);
$ mpdf-> Output ($ filename.'. pdf',
\Mpdf\Output\Destination::DOWNLOAD);
EXCEL:
$spreadsheet = new Spreadsheet(); /*----Spreadsheet object-----*/
$Excel_writer = new Xlsx($spreadsheet); /*----- Excel (Xls) Object*/
/* ...riempiendo foglio excel con i dati */
header('Content-Type: application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet');
header('Content-Disposition:
attachment;filename="'.$filename.'.xlsx"');
header('Cache-Control: max-age=0');
$Excel_writer->save('php://output');
Thanks for your help!
for Excel files: "the file may be damaged"
My blind guess is that when you peek the file content you will find Headers already sent PHP message polluting your file. If that is so, just call ob_start() before you call any of your header()s.

Open .odp, .odt, .ods files using WebView

I'm using an UIWebView for viewing .pdf, .txt, .xls, .ppt files. I used webView loadRequest method for viewing these files and its working fine. I need to view files such as .odp, .odt, .ods etc, but its showing only blank page in UIWebView. Is there any effective method for viewing these files using UIWebView or any direct method for doing the same?
Have you tried using the UIWebView method load, specifying the MIME type? For example for an .odt file:
webView.load(loadedData as Data, mimeType: "application/vnd.oasis.opendocument.text", textEncodingName: "utf-8", baseURL: NSURL() as URL)
If that does not work, then I'm afraid you'll have to write your own open office document loader...
WebODF libs integration with UIWebView: Integrated WebODF libs with UIWebView and it's working fine. Please find the below steps
1) Load index.html file from WebODF libs on UIWebView
2) Inject .odt file On webViewDidFinishLoad using below code snippet
let jsFunction = "createEditor(\"../default.odt\", \"Test\", 375, 667)"
webView.stringByEvaluatingJavaScript(from: jsFunction)
3) Successfully load the odt file.
More information : https://github.com/kogmbh/WebODF/issues/945

Downloading a YouTube video through Wget

I am trying to download YouTube videos through Wget. The first thing necessary is to capture the URL of the actual video resource. Suppose I want to download this video: video. Opening up the page in the Firebug console reveals something like this:
The link which I have encircled looks like the link to the resource, for there we see only the video: http://www.youtube.com/v/r-KBncrOggI?version=3&autohide=1. However, when I am trying to download this resource with Wget, a 4 KB file of name r-KBncrOggI#version=3&autohide=1 gets stored in my hard-drive, nothing else. What should I do to get the actual video?
And secondly, is there a way to capture different resources for videos of different resolutions, like 360px, 480px, etc.?
Here is one VERY simplified, yet functional version of the youtube-download utility I cited on my another answer:
#!/usr/bin/env perl
use strict;
use warnings;
# CPAN modules we depend on
use JSON::XS;
use LWP::UserAgent;
use URI::Escape;
# Initialize the User Agent
# YouTube servers are weird, so *don't* parse headers!
my $ua = LWP::UserAgent->new(parse_head => 0);
# fetch video page or abort
my $res = $ua->get($ARGV[0]);
die "bad HTTP response" unless $res->is_success;
# scrape video metadata
if ($res->content =~ /\byt\.playerConfig\s*=\s*({.+?});/sx) {
# parse as JSON or abort
my $json = eval { decode_json $1 };
die "bad JSON: $1" if $#;
# inside the JSON 'args' property, there's an encoded
# url_encoded_fmt_stream_map property which points
# to stream URLs and signatures
while ($json->{args}{url_encoded_fmt_stream_map} =~ /\burl=(http.+?)&sig=([0-9A-F\.]+)/gx) {
# decode URL and attach signature
my $url = uri_unescape($1) . "&signature=$2";
print $url, "\n";
}
}
Usage example (it returns several URLs to streams with different encoding/quality):
$ perl youtube.pl http://www.youtube.com/watch?v=r-KBncrOggI | head -n 1
http://r19---sn-bg07sner.c.youtube.com/videoplayback?fexp=923014%2C916623%2C920704%2C912806%2C922403%2C922405%2C929901%2C913605%2C925710%2C929104%2C929110%2C908493%2C920201%2C913302%2C919009%2C911116%2C926403%2C910221%2C901451&ms=au&mv=m&mt=1357996514&cp=U0hUTVBNUF9FUUNONF9IR1RCOk01RjRyaG4wTHdQ&id=afe2819dcace8202&ratebypass=yes&key=yt1&newshard=yes&expire=1358022107&ip=201.52.68.216&ipbits=8&upn=m-kyX9-4Tgc&sparams=cp%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&itag=44&sver=3&source=youtube,quality=large&signature=A1E7E91DD087067ED59101EF2AE421A3503C7FED.87CBE6AE7FB8D9E2B67FEFA9449D0FA769AEA739
I'm afraid it's not that easy do get the right link for the video resource.
The link you got, http://www.youtube.com/v/r-KBncrOggI?version=3&autohide=1, points to the player rather than the video itself. There is one Perl utility, youtube-download, which is well-maintained and does the trick. This is how to get the HQ version (magic fmt=18) of that video:
stas#Stanislaws-MacBook-Pro:~$ youtube-download -o "{title}.{suffix}" --fmt 18 r-KBncrOggI
--> Working on r-KBncrOggI
Downloading `Sourav Ganguly in Farhan Akhtar's Show - Oye! It's Friday!.mp4`
75161060/75161060 (100.00%)
Download successful!
stas#Stanislaws-MacBook-Pro:~$
There might be better command-line YouTube Downloaders around. But sorry, one doesn't simply download a video using Firebug and wget any more :(
The only way I know to capture that URL manually is by watching the active downloads of the browser:
That largest data chunks are video data, so you can copy its URL:
http://s.youtube.com/s?lact=111116&uga=m30&volume=4.513679238953965&sd=BBE62AA4AHH1357937949850490&rendering=accelerated&fs=0&decoding=software&nsivbblmax=679542.000&hcbt=105.345&sendtmp=1&fmt=35&w=640&vtmp=1&referrer=None&hl=en_US&nsivbblmin=486355.000&nsivbblmean=603805.166&md=1&plid=AATTCZEEeM825vCx&ns=yt&ptk=youtube_none&csipt=watch7&rt=110.904&tsphab=1&nsiabblmax=129097.000&tspne=0&tpmt=110&nsiabblmin=123113.000&tspfdt=436&hbd=30900552&et=110.146&hbt=30.770&st=70.213&cfps=25&cr=BR&h=480&screenw=1440&nsiabblmean=125949.872&cpn=JlqV9j_oE1jzk7Zc&nsivbblc=343&nsiabblc=343&docid=r-KBncrOggI&len=1302.676&screenh=900&abd=1&pixel_ratio=1&bc=26131333&playerw=854&idpj=0&hcbd=25408143&playerh=510&ldpj=0&fexp=920704,919009,922403,916709,912806,929110,928008,920201,901451,909708,913605,925710,916623,929104,913302,910221,911116,914093,922405,929901&scoville=1&el=detailpage&bd=6676317&nsidf=1&vid=Yfg8gnutZoTD4G5SVKCxpsPvirbqG7pvR&bt=40.333&mos=0&vq=auto
However, for a large video, this will only return a part of the stream unless you figure out the URL query parameter responsible for stream range to be downloaded and adjust it.
A bonus: everything changes periodically as YouTube is constantly evolving. So, don't do that manually unless you carve pain.

Resources