Giter Site home page Giter Site logo

ios-htmltopdf's Introduction

iOS-htmltopdf

This class enables simple URL-based PDF creation. Pages are created the exact same way they would be if the user printed the content on an iOS device (very similar as well as OS X print output).

Example code:

self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:
    [NSURL URLWithString:@"http://url.com"]
     pathForPDF:[@"~/Documents/demo.pdf" stringByExpandingTildeInPath]
     delegate:self
     pageSize:kPaperSizeA4
     margins:UIEdgeInsetsMake(10, 5, 10, 5)];

or using block syntax

self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:[NSURL URLWithString:@"http:/url.com"]
    pathForPDF:[@"~/Documents/blocksDemo.pdf" stringByExpandingTildeInPath]
    pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5)
    successBlock:^(NDHTMLtoPDF *htmlToPDF) {
         NSLog(@"HTMLtoPDF did succeed (%@ / %@)", htmlToPDF, htmlToPDF.PDFpath);
    } errorBlock:^(NDHTMLtoPDF *htmlToPDF) {
          NSLog(@"HTMLtoPDF did fail (%@)", htmlToPDF);
    }];

You can also use the alternative following code to generate PDF directly from HTML string, without using an URL. This is useful if you want your PDF generator to work offline or if you don't want to write first your code into a local file (you can then use NSURL with a local file through fileURLWithPath:) :

+ (id)createPDFWithHTML:(NSString*)HTML pathForPDF:(NSString*)PDFpath delegate:(id <NDHTMLtoPDFDelegate>)delegate pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins;
+ (id)createPDFWithHTML:(NSString*)HTML baseURL:(NSURL*)baseURL pathForPDF:(NSString*)PDFpath delegate:(id <NDHTMLtoPDFDelegate>)delegate pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins;
+ (id)createPDFWithHTML:(NSString*)HTML pathForPDF:(NSString*)PDFpath pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins successBlock:(NDHTMLtoPDFCompletionBlock)successBlock errorBlock:(NDHTMLtoPDFCompletionBlock)errorBlock;
+ (id)createPDFWithHTML:(NSString*)HTML baseURL:(NSURL*)baseURL pathForPDF:(NSString*)PDFpath pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins successBlock:(NDHTMLtoPDFCompletionBlock)successBlock errorBlock:(NDHTMLtoPDFCompletionBlock)errorBlock;

A paper size is only defined by a rect (e.g. kPaperSizeA4 = CGSizeMake(595.2,841.8)).

Please, be sure to create a property (e.g. PDFCreator) as NDHTMLtoPDF works asynchronously using UIWebView.

Feel free to contact me if you have any question !

@cwehrung

ios-htmltopdf's People

Contributors

bigtunacan avatar brettohland avatar fblondiau avatar henneonrails avatar iclems avatar martinjuhasz avatar zeveisenberg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ios-htmltopdf's Issues

pod update not getting latest version

Hello,

I'm not able to get the latest version (1.1.0, as written in the project's podspec). Is it because there's no release with that number? Would it be possible to add a release in order to let pod command retrieve that version?
It is important because the latest version removes UIWebView dependency, which - if present - will result in an App Store rejection after next December.
Thanks

Unwanted scale factor when rendering pages

Hello.

Ive been trying to use the library to create a pdf from a simple html with a fixed pixel size. However the resulting page is always 80% smaller than it should be. Changing the viewport meta tag does not seem to make any difference. The page should fill the screen with kPaperSizeLetter. Ive pasted the code,html and resulting pdf. Am I missing something?

Thank you. Any help much appreciated.

delegateDemo.pdf

self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:[NSURL fileURLWithPath:srcPath]
pathForPDF:[@"~/Documents/delegateDemo.pdf" stringByExpandingTildeInPath]
delegate:self
pageSize:kPaperSizeLetter
margins:UIEdgeInsetsMake(0, 0, 0, 0)];

Test2.txt

Hyperlink not working

If we use tag for hyperlink in html template and convert to pdf. link is not clickable in pdf file.

Contradicting licenses

The licenses are contradicting:
LICENSE claims MIT-license
NDHTMLtoPDF.m claims GPL license

Images not come in generated pdf

i create html and put it my bundle. this html contain image that i also put i my application bundle.
the image also display in my simulator webview.
but when i try to make pdf then generated pdf dose not contain my images.
please let me know any thing i need to modify to get pdf with my images.

Crash on createPDFWithHTML

In iOS 7, getting a looping crash on this call

[NDHTMLtoPDF createPDFWithHTML:emailBody pathForPDF:_targetPath pageSize:kPaperSizeLetter margins:UIEdgeInsetsMake(10, 5, 10, 5) successBlock:^(NDHTMLtoPDF *htmlToPDF) {
                    NSLog(@"Success - %@", htmlToPDF);
                    [self pdfCompleted];
                } errorBlock:^(NDHTMLtoPDF *htmlToPDF) {

                    NSLog(@"Fail - %@", htmlToPDF);
                    if (_failure) {
                        _failure(@"Issue building pdf.  Please try again.");
                    }
                }];

screen shot 2014-01-31 at 9 21 26 am

This was working fine before that last update.

increase margin for first page

Hi

I used this class to print pdf from HTML string, I need to add header only for the first page and increase the TOP MARGIN only for the first page how could I do like this ?

Code edited as below:

- (NSData*) printToPDF
{
    NSMutableData *pdfData = [NSMutableData data];
    
    UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil );
        
    [self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
    
    CGRect bounds = UIGraphicsGetPDFContextBounds();
        
    for ( int i = 0 ; i < self.numberOfPages ; i++ )
    {
        UIGraphicsBeginPDFPage();
        
        [self drawPageAtIndex: i inRect: bounds];
        [self drawFooterForPageAtIndex:i inRect:bounds];
        
        if (i == 0) {
            [self drawHeaderForPageAtIndex:i inRect:bounds];

        }
    }
    
    UIGraphicsEndPDFContext();
        
    return pdfData;
}

-(void)drawHeaderForPageAtIndex:(NSInteger)pageIndex inRect:(CGRect)headerRect {
    
    CGPoint startPoint = CGPointMake(headerRect.origin.x, headerRect.origin.y + headerRect.size.height - 1);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    
    
    CGContextBeginPath(context);
    CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextMoveToPoint(context, startPoint.x + 5, 50);
    CGContextAddLineToPoint(context, headerRect.size.width - 5, 50);
    CGContextStrokePath(context);

}

Correct podspec warnings

Getting these warnings on pod install and sudo pod install

[!] Unable to read the license file .../Pods/iOS-htmltopdf/LICENSE for the spec iOS-htmltopdf (0.0.1)

[!] Unable to read the license file .../Pods/iOS-htmltopdf/LICENSEfor the speciOS-htmltopdf (0.0.1)`

Crashes on iOS8.1

I have been using this code for a while and it worked perfectly. However, when I try to run the same code on iOS8.1 there is a crash in the printToPDF function on the call to drawPageAtIndex.

Is anyone else seeing the same problem?

PDF coming in two pages

Hi
In my app, I generate a HTML string fetching values from the database. Then I use this HTML string (myHTML) to generate a PDF file using NDHTMLtoPDF. Code below:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"/Invoice.pdf"];
self.PDFCreator = [NDHTMLtoPDF createPDFWithHTML:myHTML pathForPDF:filePath delegate:self pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5)];

Problem us that for many HTML's the PDF comes in two pages, even though the HTML is one page only. Some space is left below. The below HTML file is one such example.

https://www.dropbox.com/s/78ejvq4c82v8010/Invoice%20%281%29.html?dl=0

Can you please check this HTML file and let me know why the PDF for this comes in two pages?

Offline PDF with images.

Is there any way to generate a pdf from a local html string that contains images saved in the "Documents" folder?

Images missing after change to WKWebView

Hello,

I suddenly changed from an old version of NDHTMLtoPDF with UIWebView to the current version with WKWebView. Then problem now is, that I'm missing the images in the pdf. Is this a bug or do I need to change something in the code?

Code for the image (the logo)

NSString *fileURLString = [[[NSBundle mainBundle] URLForResource:@"Logo" withExtension:@"png"] absoluteString];
[htmlStrForPDF appendString:[NSString stringWithFormat:@"<td style=\"border-style:hidden\"; align=\"right\"><img src=\"%@\"/ alt=\"Logo\"; style=\"width:74px; height:50px\"></td>", fileURLString]];
[htmlStrForPDF appendString:@"</tr></table>"];

Code for creating the pdf

PlanExport *export = [[PlanExport alloc] init];                                                   
NSMutableString *htmlStrForPDF = [export createPDFPlan];
CGSize paperSize = CGSizeMake(839, 595); // DIN A4

NSString *ns_pathForFile = [NSString stringWithFormat:@"%@.%@",LocalizedString(@"PlanFileName", nil), LocalizedString(@"ExportFormatPDF", nil)];

self.PDFCreator = [NDHTMLtoPDF createPDFWithHTML:htmlStrForPDF pathForPDF:[AppCommon GetPathForFile:ns_pathForFile] pageSize:paperSize margins:UIEdgeInsetsMake(10, 15, 20, 15) successBlock:^(NDHTMLtoPDF *htmlToPDF) {
   NSString *result = [NSString stringWithFormat:@"HTMLtoPDF did succeed (%@ / %@)", htmlToPDF, htmlToPDF.PDFpath];
   NSLog(@"%@",result);
   
   // Send the generated file through Email.
   [self showEmail];
   
} errorBlock:^(NDHTMLtoPDF *htmlToPDF) {
   NSString *result = [NSString stringWithFormat:@"HTMLtoPDF did fail (%@)", htmlToPDF];
   NSLog(@"%@",result);
}];

Convert multiple HTML to multiple pdf using a for loop.

Hi, I'm trying to convert multiple html file to multiple pdf file using a for loop, however, the app crashes with Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT).

Why?

Here's the code I'm using:

for (int i=0; i<= 47; i++) {

    NSString *inputHTMLfileName = [NSString stringWithFormat:@"wkhtml_tempfile_%d",j];
    NSString *outputPDFfileName = [NSString stringWithFormat:@"~/Documents/%d_delegateDemo%d.pdf",loop,j];

    NSURL *htmlFileUrl = [[NSBundle mainBundle]
                          URLForResource:inputHTMLfileName withExtension:@"html"];


    // Check for existing pdf file and remove it
    NSError *pdfDeleteError;
    if ([[NSFileManager defaultManager] fileExistsAtPath:outputPDFfileName]){
        //removing file
        if (![[NSFileManager defaultManager] removeItemAtPath:outputPDFfileName error:&pdfDeleteError]){

            NSString * errorMessage = [NSString stringWithFormat:@"wk %d Could not remove old pdf files. Error:%@",j, pdfDeleteError];
            NSLog(@"%@",errorMessage);
        }
    }

    self.PDFCreator = [NDHTMLtoPDF createPDFWithURL:htmlFileUrl pathForPDF:[outputPDFfileName stringByExpandingTildeInPath] pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5) successBlock:^(NDHTMLtoPDF *htmlToPDF) {
        NSString *result = [NSString stringWithFormat:@"HTMLtoPDF did succeed (%@ / %@)", htmlToPDF, htmlToPDF.PDFpath];
        NSLog(@"%@",result);
        self.resultLabel.text = result;
    } errorBlock:^(NDHTMLtoPDF *htmlToPDF) {
        NSString *result = [NSString stringWithFormat:@"HTMLtoPDF did fail (%@)", htmlToPDF];
        NSLog(@"%@",result);
        self.resultLabel.text = result;
    }];
}

iPad pdf generate issue

html to pdf works fine on iPhone but when i open in iPad it's not work. can you please do something ?

Swift compatible?

I tried it in my swift project and it seems to crash every time, I tried both createPDFWithHTML and NDHTMLtoPDF.createPDFWithHTML, with no luck

let PDFCreator = NDHTMLtoPDF.createPDFWithHTML(htmlString.readString(),
baseURL: NSURL(fileURLWithPath: htmlString.path_string),
pathForPDF: toFile,
pageSize: CGSizeMake(595.2,841.8),
margins: UIEdgeInsetsMake(10, 5, 10, 5),
successBlock: nil,
errorBlock: nil)

    print("open " + toFile)

    NDHTMLtoPDF.createPDFWithHTML(htmlString.readString(),
        baseURL: NSURL(fileURLWithPath: htmlString.path_string),
        pathForPDF: toFile,
        delegate: nil,
        pageSize: CGSizeMake(595.2,841.8),
        margins: UIEdgeInsetsMake(10, 5, 10, 5))

[Pods] Unable to read the license file

Hi,
I got a warning while executing "pod install" :

[!] Unable to read the license file `/path/to/project/Pods/iOS-htmltopdf/LICENSE` for the spec `iOS-htmltopdf (0.0.1)`

Indeed, the file is not downloaded with pod.

HTMLtoPDF did fail error

everytime i run the project and click on the button to generate pdf i get this error HTMLtoPDF did fail.please help me out

page breaks

CSS rule page-break-after seems to cause
[self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
to get caught in a loop until memory exhaustion.

CSS rule page-break-before works perfectly.

Might be worth a note in the readme explaining this.

not recognising href tag

Hello

PDF converted perfectly fine but when it comes to click event on some text or part of pdf it is not working.

There is on section in pdf "click here" which opens url which is not working in PDF.

Can you please guide if it is possible?

Html Code :- "Click here"

Thanks

Balnk page because of page-break trough CSS

I don't know if the bug is in uiwebview or in this library. But I've put div's in my html-code with a class pagebreak. It does a page break, but with an extra blank page.
How do I get rid of the blank page.

    @media all {
        .pagebreak  { display: none; }
    }

    @media print {
        .pagebreak  { display: block; page-break-before: always; }
    }

Footer for pdf

Hi, How can we add footer in pdf. I want to add a footer on every page of pdf, but not getting a work around.

EXC_BAD_ACCESS

It is generating a EXC_BAD_ACCESS Message when using your example:

libobjc.A.dylib`objc_msgSend:
0x17b708c:  movl   8(%esp), %ecx
0x17b7090:  movl   4(%esp), %eax
0x17b7094:  testl  %eax, %eax
0x17b7096:  je     0x17b70e8                 ; objc_msgSend + 92
0x17b7098:  movl   (%eax), %edx
0x17b709a:  pushl  %edi
0x17b709b:  movl   8(%edx), %edi

This is the code:

NSString *documentsDirectory = [NSHomeDirectory()
                                    stringByAppendingPathComponent:@"Documents"];

    NSString *filePath = [documentsDirectory
                          stringByAppendingPathComponent:@"demo.pdf"];
        _PDFCreator = [NDHTMLtoPDF createPDFWithHTML:[self generateHTMLforPDF] pathForPDF:filePath delegate:nil pageSize:kPaperSizeA4 margins:UIEdgeInsetsMake(10, 5, 10, 5)];

support android?

i would like to use these project (htmltopdf) to android application development.

suppport android ? or ios only

thank you

createPDFWithHTML and images

I am having issues to have images show up with the createPDFWithHTML. In the PDF File that is created I see the image tag but not the actual image.

Since the images are stored as external binary files in Core Data, how would you pass each image as an HTML tag?

<img src="file:ImageFromCoreData">
or 
<img src="ImageFromCoreData">

Any ideas?

Please add semantic version tags

I’ve recently added iOS-htmltopdf to the CocoaPods package manager repo.

CocoaPods is a tool for managing dependencies for OS X and iOS Xcode projects and provides a central repository for iOS/OS X libraries. This makes adding libraries to a project and updating them extremely easy and it will help users to resolve dependencies of the libraries they use.

However, iOS-htmltopdf doesn't have any version tags. I’ve added the current HEAD as version 0.0.1, but a version tag will make dependency resolution much easier.

Semantic version tags (instead of plain commit hashes/revisions) allow for resolution of cross-dependencies.

In case you didn’t know this yet; you can tag the current HEAD as, for instance, version 1.0.0, like so:

$ git tag -a 1.0.0 -m "Tag release 1.0.0"
$ git push --tags

Multiple HTML files to one PDF

Guys, I'm having a very difficult time trying to generate one PDF with multiple pages, each page being a different HTML file.
I can generate N pdf files each one having the content of one of the HTML files, but I want to group all that in just one PDF.
In time, I can't use the content coming from a UIWebView. It has to come from a URL.
Anyone has any tips on this?
Thank you in advance!

Content is cropped if too wide

If the content is too wide, the content is cropped. It works with the height as it will then span multiple pages.

A solution would be to scale the content to fit the available width. I've tried but I can't seem to succeed with this.

Do you know how to do it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.