SORU
6 Aralık 2010, PAZARTESİ


iOS SDK - Programlı bir PDF dosyası oluşturmak

KullanarakCoreGraphicsçerçeve sıkıcı iş, Program aracılığıyla bir PDF dosyası çizim olduğunda kişisel görüşümü.

Program aracılığıyla oluşturmak istiyorumPDFbenim app boyunca görünümlerinden çeşitli nesneleri kullanarak.

Eğer öğreticiler iOS SDK, kütüphanede bir damla belki etrafında herhangi bir iyi PDF olup olmadığını merak ediyorum.

Bu eğitimde gördüm, PDF Creation Tutorial, C. ama daha Arayan çoğunlukla yazılı Objective-C tarzı oldu. Bu çizgiler ve diğer nesnelerin yerleştirileceği da saçma bir yol gibi bir PDF dosyası için, hesaplamak zorunda yazmak gibi görünüyor.

void CreatePDFFile (CGRect pageRect, const char *filename) 
{   
    // This code block sets up our PDF Context so that we can draw to it
    CGContextRef pdfContext;
    CFStringRef path;
    CFURLRef url;
    CFMutableDictionaryRef myDictionary = NULL;

    // Create a CFString from the filename we provide to this method when we call it
    path = CFStringCreateWithCString (NULL, filename,
                                      kCFStringEncodingUTF8);

    // Create a CFURL using the CFString we just defined
    url = CFURLCreateWithFileSystemPath (NULL, path,
                                         kCFURLPOSIXPathStyle, 0);
    CFRelease (path);
    // This dictionary contains extra options mostly for 'signing' the PDF
    myDictionary = CFDictionaryCreateMutable(NULL, 0,
                                             &kCFTypeDictionaryKeyCallBacks,
                                             &kCFTypeDictionaryValueCallBacks);

    CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File"));
    CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name"));
    // Create our PDF Context with the CFURL, the CGRect we provide, and the above defined dictionary
    pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary);
    // Cleanup our mess
    CFRelease(myDictionary);
    CFRelease(url);
    // Done creating our PDF Context, now it's time to draw to it

    // Starts our first page
    CGContextBeginPage (pdfContext, &pageRect);

    // Draws a black rectangle around the page inset by 50 on all sides
    CGContextStrokeRect(pdfContext, CGRectMake(50, 50, pageRect.size.width - 100, pageRect.size.height - 100));

    // This code block will create an image that we then draw to the page
    const char *picture = "Picture";
    CGImageRef image;
    CGDataProviderRef provider;
    CFStringRef picturePath;
    CFURLRef pictureURL;

    picturePath = CFStringCreateWithCString (NULL, picture,
                                             kCFStringEncodingUTF8);
    pictureURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), picturePath, CFSTR("png"), NULL);
    CFRelease(picturePath);
    provider = CGDataProviderCreateWithURL (pictureURL);
    CFRelease (pictureURL);
    image = CGImageCreateWithPNGDataProvider (provider, NULL, true, kCGRenderingIntentDefault);
    CGDataProviderRelease (provider);
    CGContextDrawImage (pdfContext, CGRectMake(200, 200, 207, 385),image);
    CGImageRelease (image);
    // End image code

    // Adding some text on top of the image we just added
    CGContextSelectFont (pdfContext, "Helvetica", 16, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode (pdfContext, kCGTextFill);
    CGContextSetRGBFillColor (pdfContext, 0, 0, 0, 1);
    const char *text = "Hello World!";
    CGContextShowTextAtPoint (pdfContext, 260, 390, text, strlen(text));
    // End text

    // We are done drawing to this page, let's end it
    // We could add as many pages as we wanted using CGContextBeginPage/CGContextEndPage
    CGContextEndPage (pdfContext);

    // We are done with our context now, so we release it
    CGContextRelease (pdfContext);
}

DÜZENLEME:İşte iPhone projesinde GitHub using libHaru bir örnek.

CEVAP
6 Aralık 2010, PAZARTESİ


Bir kaç şey...

İlk olarak, bozuk PDF'leri sonuçları iOS CoreGraphics PDF nesil bir hata var. Bu sorun ve iOS 4.1 (4.2 iOS test etmedim) de dahil olmak üzere, var olduğunu biliyorum. Sorun tipleri ile ilgilidir ve eğer PDF metin eklerseniz, yalnızca gösterir. Belirti, PDF oluşturma, hata ayıklama hataları bu gibi konsol göreceksiniz

<Error>: can't get CIDs for glyphs for 'TimesNewRomanPSMT'

Zor yönü ortaya çıkan bazı PDF PDF okuyucularda iyi hale getirecek, ancak başka yerlerde işlemek için başarısız. Bu yüzden, eğer kontrol yazılımı kullanılacak açık PDF, sen-ebilmek muktedir görmezden bu sorun (örneğin, eğer sadece niyetinde görüntü PDF üzerinde iPhone veya Mac masaüstü, olmalısın da iyi kullanarak CoreGraphics). Eğer herhangi bir yerde çalışan bir PDF oluşturmak istiyorsanız, ancak daha sonra bu sorunu daha yakından bakmak gerekir. Burada bazı ek bilgi:

http://www.iphonedevsdk.com/forum/iphone-sdk-development/15505-pdf-font-problem-cant-get-cids-glyphs.html#post97854

Geçici bir çözüm olarak, başarıyla CoreGraphics PDF nesil için bir yedek olarak iPhone libHaru kullandım. Biraz zor benim proje ile inşa libHaru başlangıçta başlamıştı, ama proje benim kurulum düzgün bir şekilde geldikten sonra, benim ihtiyaçları için iyi çalıştı.

İkinci olarak, PDF biçimi/düzeni bağlı olarak, Interface Builder "şablon" PDF çıkış için. bir hizmet veren bir görünüm oluşturmak için kullanabilirsiniz Sonra Görünüm yüklemek için kod yazarsınız, herhangi bir veri (örneğin, set UİLabels için metin, vb.) doldurmak, sonra render PDF görünüm öğelerini tek tek. Diğer bir deyişle, kullanım koordinatları, yazı, resim, vb belirtmek için İB. ve yazmak çeşitli unsurlar (örneğin, UILabel, UIImageView, vb.) işlemek için kod sabit kod gerek yok çok genel bir şekilde her şeyi. Bu yaklaşım kullandım ve benim ihtiyaçları için mükemmel çalıştı. Yine de bu durum senin PDF biçimlendirme/düzen ihtiyaçlarına bağlı olarak bir anlam ifade etmiyor olabilir.

DÜZENLEME:(1 yorum yanıt)

Benim uygulama ticari bir ürünün tam kodu paylaşamam yani bir parçası, ama genel bir özet verebilirim:

Bir ben yarattım .bir görünüm ile dosya xib ve 850 x 1100 (PDF bu kolay tasarım-zaman/koordinatları yapar 8,5 x 11 inç hedefleyen, oldu) görünümü bulunur.

Kodu, görünüm yük:

- (UIView *)loadTemplate
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ReportTemplate" owner:self options:nil];
    for (id view in nib) {
        if ([view isKindOfClass: [UIView class]]) {
            return view;
        }
    }

    return nil;
}

O zaman farklı öğeleri doldurun. Etiketler uygun elemanı bulmak için kullandım, ama bu başka yolları da yapabilirsin. Örnek:

UILabel *label = (UILabel *)[templateView viewWithTag:TAG_FIRST_NAME];
if (label != nil) {
    label.text = (firstName != nil) ? firstName : @"None";

Sonra PDF dosyası görünümü işlemek için bir fonksiyon çağırıyorum. Bu işlev özyinelemeli olarak görünüm hiyerarşisi yürür ve her bir küme oluşturur. Projem için, sadece Etiket, İmageView, ve Görünümü (iç içe geçmiş bir görünüm için) destek istiyorum:

- (void)addObject:(UIView *)view
{
    if (view != nil && !view.hidden) {
        if ([view isKindOfClass:[UILabel class]]) {
            [self addLabel:(UILabel *)view];
        } else if ([view isKindOfClass:[UIImageView class]]) {
            [self addImageView:(UIImageView *)view];
        } else if ([view isKindOfClass:[UIView class]]) {
            [self addContainer:view];
        }
    }
}

Örnek olarak, burada addİmageView benim uygulama (HPDF_ fonksiyonları libHaru ait):

- (void)addImageView:(UIImageView *)imageView
{
    NSData *pngData = UIImagePNGRepresentation(imageView.image);
    if (pngData != nil) {
        HPDF_Image image = HPDF_LoadPngImageFromMem(_pdf, [pngData bytes], [pngData length]);
        if (image != NULL) {
            CGRect destRect = [self rectToPDF:imageView.frame];

            float x = destRect.origin.x;
            float y = destRect.origin.y - destRect.size.height;
            float width = destRect.size.width;
            float height = destRect.size.height;

            HPDF_Page page = HPDF_GetCurrentPage(_pdf);
            HPDF_Page_DrawImage(page, image, x, y, width, height);
        }
    }
}

Umarım bu size bir fikir verir.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • 10 Daughters, 2 Sons

    10 Daughters

    10 Mart 2009
  • Madeon

    Madeon

    31 Ocak 2010
  • TopDJMag TV

    TopDJMag TV

    29 Temmuz 2010